1.继承实例分析。。。

 1  class Animal {
 2 
 3     int eye=2;                //定义动物属性有眼睛和腿
 4     
 5     int leg=4;
 6     
 7     public void eat()
 8     {                                             //无参构造方法
 9         System.out.println("正在吃。。。。。。");
10     }
11     public void run()
12     {
13         System.out.println("正在飞。。。。。。");
14     }
15 }
16 
17  class Bird extends Animal {          //小鸟类继承父类动物
18 
19     public void fly(){                      //定义小鸟类   属性在飞
20         
21         System.out.println("正在飞");
22     }
23     
24 }
25 
26 public class Inherite {
27 
28     public static void main(String[] args) {      //创建Inherite类调用父类属性方法
29         
30         Animal an=new Animal();               //创建Animal类的对象并为其分配内存
31         
32         System.out.println(an.eye);
33         
34         System.out.println(an.leg);
35         
36         an.eat();
37         
38         an.run();
39         
40         System.out.println("%%%%%%%%%%");
41         
42         Bird bird1=new Bird();            //创建鸟的对象并为其分配内存
43         
44         System.out.println(bird1.eye);
45         
46         System.out.println(bird1.leg);
47 
48         bird1.eat();
49         
50         bird1.fly();
51     }
52 
53 }

4
正在吃。。。。。。
正在飞。。。。。。
%%%%%%%%%%
2
4
正在吃。。。。。。
正在飞

在Bird类中并没有定义eye属性但是因为他继承了Animal类,所以可以直接输出System.out.println (bird1.eye);
也可以重新给leg属性赋值,Animal类中的方法可以直接调用。

原文地址:https://www.cnblogs.com/as1234as/p/5144533.html