用Java设计一个dog,属性有name,color,age,输出age,返回name,接受一个颜色值,用其修改自身的color,接受一个i,计算i的阶乘
时间: 2024-09-28 13:11:41 浏览: 34
使PHP自定义函数返回多个值
在Java中,我们设计一个Dog类,它将包含name、color和age这三个属性,并提供相应的getter和setter方法,以及一个方法来计算输入整数的阶乘,以及一个方法用于改变自身的颜色。以下是详细的类设计:
```java
public class Dog {
private String name;
private String color;
private int age;
// 构造函数
public Dog(String name, String color, int age) {
this.name = name;
this.color = color;
this.age = age;
}
// getter and setter methods
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Method to calculate factorial
public long factorial(int i) {
if (i == 0 || i == 1) {
return 1;
} else {
return i * factorial(i - 1);
}
}
// Method to change color with a given input
public void updateColor(String newColor) {
this.color = newColor;
}
}
```
你可以像下面这样使用这个类:
```java
Dog dog = new Dog("Max", "Brown", 5);
System.out.println("Age: " + dog.getAge());
System.out.println("Name: " + dog.getName());
// Update color
dog.updateColor("Black");
System.out.println("New Color: " + dog.getColor());
// Calculate factorial
long fact = dog.factorial(3);
System.out.println("Factorial of 3: " + fact);
```
阅读全文