您的位置:首页 > 其它

1.继承实例分析。。。

2016-01-20 11:27 288 查看
class Animal {

int eye=2;                //定义动物属性有眼睛和腿

int leg=4;

public void eat()
{                                             //无参构造方法
System.out.println("正在吃。。。。。。");
}
public void run()
{
System.out.println("正在飞。。。。。。");
}
}

class Bird extends Animal {          //小鸟类继承父类动物

public void fly(){                      //定义小鸟类   属性在飞

System.out.println("正在飞");
}

}

public class Inherite {

public static void main(String[] args) {      //创建Inherite类调用父类属性方法

Animal an=new Animal();               //创建Animal类的对象并为其分配内存

System.out.println(an.eye);

System.out.println(an.leg);

an.eat();

an.run();

System.out.println("%%%%%%%%%%");

Bird bird1=new Bird();            //创建鸟的对象并为其分配内存

System.out.println(bird1.eye);

System.out.println(bird1.leg);

bird1.eat();

bird1.fly();
}

}


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

在Bird类中并没有定义eye属性但是因为他继承了Animal类,所以可以直接输出System.out.println (bird1.eye);
也可以重新给leg属性赋值,Animal类中的方法可以直接调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: