第一部分:
package Day02;
public 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("吃饭");
}
public void sleep() {
System.out.println("睡觉");
}
}
第二部分:
package Day02;
public class Cat extends Animal{//子类 猫类 继承父类
public void eat() {//子类重写父类方法
System.out.println("猫吃鱼");
}
public void catchMouse() {
System.out.println("猫抓老鼠");
}
}
第三部分:
package Day02;
public class Dog extends Animal {//子类 狗类 继承父类
private String name;//子类独有属性 封装
public Dog() {//无参构造
}
public Dog(String color,int leg,String name) {//有参构造
super(color,leg);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat() {//子类重写父类方法
System.out.println("狗吃骨头");
}
public void lookHome() {
System.out.println("看家");
}
}
第四部分:
package Day02;
//测试结果
public class Day02_Test01 {
public static void main(String[] args) {//主方法
Cat c = new Cat();
c.setColor("橘黄色");//set(...) 设置 get(...)获取
c.setLeg(4);
System.out.println(c.getColor() + "... " + c.getLeg());
c.sleep();
c.eat();
c.catchMouse();
System.out.println("~~~~~~~~~~~~~~~~~~~~~");
Dog d = new Dog("黑色",4,"拉布拉多");
d.getColor();
d.getLeg();
d.getName();
System.out.println(d.getColor() + "... " + d.getLeg() + "..." + d.getName());
d.eat();
d.sleep();
d.lookHome();
}
}
运行结果: