package Lianxi2;
public class Animal {
private String name;
private String color;
Animal(){}
Animal(String name,String color){
setColor(color);
setName(name);
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public void setName(String name) {
this.name = name;
}
public void setColor(String color) {
this.color = color;
}
public void show(){
System.out.println("名字"+name+" 颜色"+ color);
}
}
package Lianxi2;
public class Dog extends Animal {
private int tooth;
public Dog(){}
public Dog(String name,String color,int tooth){
super(name,color);
this.tooth=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());
}
}
package Lianxi2;
public class DogTest {
public static void main(String[] args){
//使用无参构造worker类型对象并打印
Dog t1 = new Dog();
t1.show();
Dog t2 = new Dog(“wangcai”,“baise”,10);
t2.show();
}
}
子类继承的时候:在构造方法中继承父类的成员变量,然后写自己的特有的方法。
重写的时候:也要先super一下父类的show。然后加上想要比父类添加的内容。