再次感觉到良好的书写习惯的重要!
/*
* A:继承(extends)
* 让类与类之间产生关系,子父类关系
* B:继承案例演示:
* 动物类,猫类,狗类
* 定义两个属性(颜色,腿的个数)两个功能(吃饭,睡觉)
* C:案例演示
* 使用继承前
* D:案例演示
* 使用继承后
*/
class Demo_Extends_Animals {
public static void main(String[] args) {
Cat c = new Cat ("白色" , 4);
System.out.println(c.getColor() + "......de猫....." + c.getLeg());
c.eat();
c.sleep();
System.out.println("---------------------------------------------");
Dog d = new Dog ("黑色" , 4);
System.out.println(d.getColor() + "......de狗....." + d.getLeg());
d.eat();
d.sleep();
}
}
class Animals {
private String color;
private int leg;
public Animals () {}
public Animals (String color , int leg ) {
this.color = color;
this.leg = leg;
}
public void setColor (String color) {
this.color = color;
}
public String getColor () {
return color;
}
public void setLeg (int leg) {
this.leg = leg;
}
public int getLeg () {
return leg;
}
public void eat () {
System.out.println("吃饭");
}
public void sleep () {
System.out.println("睡觉");
}
}
class Cat extends Animals {
public Cat () {}
public Cat (String color , int leg) {
super (color , leg);
}
}
class Dog extends Animals {
public Dog () {}
public Dog (String color , int leg) {
super(color , leg);
}
}
|
|