JAVA重写

概念

从父类中继承下来的方法不满足子类的需求时,就需要在子类中重新写 一个和父类一样的方法来覆盖从父类中继承下来的版本,该方式就叫做 方法的重写(Override)。
方法重写的原则

• 要求方法名相同、参数列表相同以及返回值类型相同,从Java5开始允许 返回子类类型。

• 要求方法的访问权限不能变小,可以相同或者变大。 • 要求方法不能抛出更大的异常(异常机制)。

 code:

public class Animal {
private String name;
private String color;

public Animal() {
}
public Animal(String name, String color) {
setName(name);
setColor(color);
}

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 void show() {
// sout 回车 生成打印的语句
System.out.println("名字:" + getName() + ", 颜色:" + getColor());
}
}

public class Dog extends Animal {
private int tooth;

public Dog() {
super(); // 表示调用父类的无参构造方法 自动保存
}
public Dog(String name, String color, int tooth) {
super(name, color); // 表示调用父类的有参构造方法
setTooth(tooth);
}

public int getTooth() {
return tooth;
}
public void setTooth(int tooth) {
if (tooth > 0) {
this.tooth = tooth;
} else {
System.out.println("牙齿数量不合理哦!!!");
}
}

@Override
public void show() {
super.show();
System.out.println("牙齿数量是:" + getTooth());
}
}

public class DogTest {

public static void main(String[] args) {
// 1.使用无参方式构造Dog类型的对象并打印特征
Dog d1 = new Dog();
d1.show(); // null null 0

// 2.使用有参方式构造Dog类型的对象并打印特征
Dog d2 = new Dog("旺财", "白色", 10);
d2.show(); // 旺财 白色 10
}
}
原文地址:https://www.cnblogs.com/goldenwangyi/p/15031638.html