JAVA 继承

继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为。继承是通过extends关键字进行的

继承过程中的问题

```

package animal;

public class Animal {

int weight = 888;

public void eat() {

System.out.println("Animal eat");

}

public int getWeight() {

return weight;

}

public void setWeight(int weight) {

this.weight = weight;

}

}

```

```

package animal;

public class Cat extends Animal {

int weight = 1000;//与父类的变量名相同

public String string = "hahhahha";

@Override

public void eat(){

System.out.println("Cat eat");

}

public void jump(){

System.out.println("Cat jump");

}

@Override

public int getWeight() {

return weight;

}

@Override

public void setWeight(int weight) {

this.weight = weight;

}

public String getString() {

return string;

}

}

```

```

import animal.Animal;

import animal.Cat;

public class Main {

public static void main(String[] args) {


Animal animal = new Cat();//父类对象引用指向子类对象

System.out.println(animal.toString());

animal.eat();//执行的是Cat中的方法

System.out.println(animal.getWeight());//由于override了父类方法。调用的Cat中的方法,因此输出的是1000。如果需要访问父类的weight需要通过super关键字 (super.weight)

// animal.jump(); 会提示jump方法未定义向上转型时会遗失与父类对象不同的方法,而变量不会遗失

Cat cat = (Cat) animal;//向下转型,在编译时是不会报错的,运行时可能会出现ClassCastException。

System.out.println(cat.toString());

}

}

```

运行结果:

animal.Cat@6bc7c054

Cat eat

1000

animal.Cat@6bc7c054


运行结果表明:animal中指向的是cat对象。而由于cat继承自animal因此拥有animal所有非private的方法和变量。但由于是animal的引用,因此无法使用cat中与父类不同的方法。

最后建议:在需要override方法时,加上@Override的注解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容