java创建一个动物类,其中包含私有属性名称、年龄、种,后创 建方法去访问和修改这些属性的测试类
时间: 2024-05-14 14:15:59 浏览: 99
以下是Java创建一个动物类的示例代码:
```java
public class Animal {
private String name;
private int age;
private String species;
public Animal(String name, int age, String species) {
this.name = name;
this.age = age;
this.species = species;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}
```
接下来是一个简单的测试类,可以创建Animal对象并访问和修改其属性:
```java
public class AnimalTest {
public static void main(String[] args) {
Animal myAnimal = new Animal("Tom", 5, "cat");
// 访问属性
System.out.println("My animal's name is " + myAnimal.getName());
System.out.println("My animal's age is " + myAnimal.getAge());
System.out.println("My animal's species is " + myAnimal.getSpecies());
// 修改属性
myAnimal.setName("Jerry");
myAnimal.setAge(3);
myAnimal.setSpecies("mouse");
System.out.println("My animal's name is now " + myAnimal.getName());
System.out.println("My animal's age is now " + myAnimal.getAge());
System.out.println("My animal's species is now " + myAnimal.getSpecies());
}
}
```
输出结果如下:
```
My animal's name is Tom
My animal's age is 5
My animal's species is cat
My animal's name is now Jerry
My animal's age is now 3
My animal's species is now mouse
```
阅读全文