类的继承

                      类的继承

理解继承是理解面向对象编程设计的关键。

在java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类成为子类(派生类)。

在java中,不允许多继承。

除Object意外的一切类都是继承自Object类,Object是祖先类。只有它没有父类。

 

代码
public class Animal {
private int height;
private int weight;

public void setHeight(int height) {
this.height = height;
}

public void setWeight(int weight) {
this.weight = weight;
}

public int getHeight(int height) {
return height;
}

public void getWeight(int weight) {
return weight;
}

public void eat() {
System.out.println(
"animal eat");
}

public void sleep() {
System.out.println(
"animal sleep");
}

public void breath() {
System.out.println(
"animal breath");
}
}

class Fish extends Animal{

}

class Integration {
public static void main(String[] args) {
Animal an
= new Animal();
Fish fh
= new Fish();

an.breath();
fh.breath();
}
}

 

Fish是由Animal派生来的,它就继承了Animal的所有属性和方法。

鱼的呼吸方式不同于其他的动物,鱼是通过吐泡泡来完成呼吸的。所以这就要在Fish类中重写父类的方法,达到改写的目的。获得自己的呼吸方式。

class Fish extends Animal {
public void breathe() {
System.out.println(
"fish breath");
}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2010-12-20 23:23  meng72ndsc  阅读(140)  评论(0编辑  收藏  举报