第四章:继承

第一题:设计Bird,Fish类,都继承自抽象类Animal,实现其抽象方法info(),并输出它们的信息,参考运行结构如图,要求画出类图。

package WeekDemo;


public abstract class Animal {
int age; //共同属性年龄

public Animal(int age) {
super();
this.age = age;
}


public abstract void info();

}

package WeekDemo;


public class Bird extends Animal {
String color;


public Bird(int age, String color) {
super(age);
this.color = color;
}


public void info() {
System.out.println("我是一只" + color + "的鸟!\n今年" + super.age + "岁了!");


}


}

package WeekDemo;


public class Fish extends Animal {
int weight;




public Fish(int age, int weight) {
super(age);
this.weight = weight;
}






public void info() {
System.out.println("我是一只" + weight + "斤重的魚!\n今年" + super.age + "岁了!");




}


}

package WeekDemo;


public class Test11 {
public static void main(String[] args) {
Bird bird = new Bird(4,"紅色");
bird.info();
Fish fish = new Fish(2, 5);
fish.info();
}

}                                                            //测试类

第二题:兜兜家养了两只家禽:一只鸡和一只鸭。请用面向对象思想的封装,继承的特征进行描述。

package WeekDemo;


public abstract class Poultry {
private String name; //共同属性名字  
   private String hobby; //共同属性爱好  
   private String action; //共同属性行为     
 
public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getHobby() {
return hobby;
}


public void setHobby(String hobby) {
this.hobby = hobby;
}


public String getAction() {
return action;
}


public void setAction(String action) {
this.action = action;

}

}

package WeekDemo;


public class Chicken extends Poultry {
public void print() {  
        super.setName("喔喔");  
        System.out.println("我叫"+super.getName()+"是一只芦花鸡!");  
        super.setHobby("吃虫子!");  
        System.out.println("我喜欢"+super.getHobby());  
        super.setAction("打鸣!");  
        System.out.println("我会"+super.getAction());  
    }  

}  

package WeekDemo;


public class Duck extends Poultry {
public void print() {  
        super.setName("嘎嘎");  
        System.out.println("我叫"+super.getName()+"是一只斑嘴鸭!");  
        super.setHobby("吃小鱼虾!");  
        System.out.println("我喜欢"+super.getHobby());  
        super.setAction("游泳!");  
        System.out.println("我会"+super.getAction());  

    }  

}

package WeekDemo;


public class Test2 {
public static void main(String[] args) {
Chicken show = new Chicken();  
       show.print();  
       System.out.println();  
       Duck show1 = new Duck();  
       show1.print();  
}


} //测试类






猜你喜欢

转载自blog.csdn.net/liyanghahahhaha/article/details/80419627