8.6实战练习

第二题:

Bird类代码:

 1 package zuoye;
 2 
 3 public class Bird {
 4     private String name;
 5     private String yanse;
 6     public String getName() {
 7         return name;
 8     }
 9     public void setName(String name) {
10         this.name = name;
11     }
12     public String getYanse() {
13         return yanse;
14     }
15     public void setYanse(String yanse) {
16         this.yanse = yanse;
17     }
18     public Bird(String name, String yanse) {
19     
20         System.out.println("父类构造方法");
21         this.name = name;
22         this.yanse = yanse;
23         
24     }
25     public void eat()
26     {
27         System.out.println("我可以吃虫子");
28     }
29     
30     public void fly()
31     {
32         System.out.println("我可以飞");
33     }
34 
35 }
View Code

Yingwu类代码:

 1 package zuoye;
 2 
 3 public class Yingwu extends Bird {
 4 
 5     public Yingwu() {
 6         super("鹦鹉","绿色");
 7         System.out.println("子类构造方法");
 8     }
 9     
10     public void sing()
11     {
12         System.out.println("我爱唱歌");
13     }
14     public void fly()
15     {
16         System.out.println("我喜欢边飞边唱:苍茫的天涯是我的爱~");
17     }
18     
19 
20 }
View Code

Test类代码:

 1 package zuoye;
 2 
 3 public class TestBird {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Bird b1=new Bird("麻雀","灰色");
 8         System.out.println("我是"+b1.getName()+"颜色是"+b1.getYanse());
 9         b1.eat();
10         b1.fly();
11         System.out.println();
12         Yingwu y1=new Yingwu();
13         System.out.println("我是"+y1.getName()+"颜色是"+y1.getYanse());
14         y1.eat();
15         y1.sing();
16         y1.fly();
17         System.out.println();
18         Bird b2=new Yingwu();
19         System.out.println("我是"+b2.getName()+"颜色是"+b2.getYanse());
20         b2.eat();
21         b2.fly();
22         
23         
24     }
25 
26 }
View Code

第三题:

代码同上,构建子类对象时要先调用子类的构造方法,若构造方法有参数时需添加参数,然后可以继续调用子类或者父类的其他方法。

原文地址:https://www.cnblogs.com/beens/p/5261645.html