黑马程序员技术交流社区
标题:
面向对象:继承与重写
[打印本页]
作者:
shenzhinishimen
时间:
2016-6-8 21:37
标题:
面向对象:继承与重写
* 猫狗案例继承版
* 属性:毛的颜色,腿的个数
* 行为:吃饭
* 猫特有行为:抓老鼠catchMouse
* 狗特有行为:看家lookHome
public class Demo8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat c = new Cat();
c.setColor("黑色");
c.setLeg(4);
System.out.println(c.getColor() + "..." + c.getLeg());
c.eat();
c.catchMouse();
System.out.println("------------");
Dog d = new Dog("黄色", 4);
System.out.println(d.getColor() + "..." + d.getLeg());
d.eat();
d.lookHome();
}
}
class Animal {
private String color;
private int leg;
public Animal() {
}
public Animal(String color, int leg) {
this.color = color;
this.leg = leg;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getLeg() {
return leg;
}
public void setLeg(int leg) {
this.leg = leg;
}
public void eat() {
System.out.println("吃饭");
}
}
class Cat extends Animal {
public Cat() {
}
public Cat(String color, int leg) {
super(color, leg);
}
public void catchMouse() {
System.out.println("猫抓老鼠");
}
public void eat() {
System.out.println("猫吃鱼");
}
}
class Dog extends Animal {
public Dog() {
}
public Dog(String color, int leg) {
super(color, leg);
}
public void lookHome() {
System.out.println("狗会看家");
}
public void eat() {
System.out.println("狗吃肉");
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2