方法重写规则:
- 方法名相同
- 参数列表相同
- 返回值类型相同或者是其子类
- 访问权限不能严于父类
方法重写注意
- 子类根据需求对从父类继承的方法进行重新编写
- 重写时,可以用super.方法的方式来保留父类的方法
- 构造方法不能被重写
第一部分、创建一个动物类
public class Animal {
private String name;
private int health;
private int love;
public Animal() {
super();//调用父类Object类里的无参构造方法
}
public Animal(String name, int health, int love) {
super();//调用父类Object类里的无参构造方法
this.name = name;
this.health = health;
this.love = love;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getLove() {
return love;
}
public void setLove(int love) {
this.love = love;
}
// 定义一个输出动物信息的方法
public void print() {
System.out.println("动物昵称:" + this.name + ",健康值:" + this.health
+ ",亲密度:" + this.love);
}
}
第二部分:创建一个动物类的子类----小狗类
public class Dog extends Animal {
private String strain;
public Dog() {
super();// 调用Animal类里的无参构造方法
}
public Dog(String name, int health, int love, String strain) {
super(name, health, love);// 调用Animal类里的有参构造方法
this.strain = strain;
}
public String getStrain() {
return strain;
}
public void setStrain(String strain) {
this.strain = strain;
}
public void print(){
super.print();
System.out.println("宠物品种:"+this.strain);
}
}
第三部分:创建一个动物类的另一个子类----猫类
public class Cat extends Animal {
private String color;
public Cat() {
super();
}
public Cat(String name, int health, int love, String color) {
super(name, health, love);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
//重新定义父类里的print()方法
public void print(){
//输出宠物的所有信息
super.print();
System.out.println("宠物颜色:"+this.color);
}
}
第四部分:创建一个测试
public class Test {
public static void main(String[] args) {
Cat cat1 = new Cat("敦敦", 88, 99, "黄色");
cat1.print();
Dog dog1 = new Dog("来福", 99, 90, "泰迪");
dog1.print();
}
}
代码测试结果



