Java中继承的使用

来源:互联网 发布:怎么在淘宝商城开店 编辑:程序博客网 时间:2024/05/22 03:47

关于java中继承的总结:

1.我们在使用继承的时候,需要清楚:子类会全部继承父类的变量/方法。对于下面的代码,则是一个错误代码,先看代码:

package liu.shen.test;public class Client {public static void main(String [] args){People stu = new Student();stu.age = 20;System.out.println(stu.age);}}

package liu.shen.test;public abstract class People {}

package liu.shen.test;public class Student extends People{int  age,height;}
为什么会是错误的代码呢?

原因如下:

(1)我们在Client类中使用的是People stu = new Student();这么一个语句来新建一个People类的对象,这个很重要!!因为即使后面的语句是new Student(),并且Student类中有int age,heigth这个属性,但是依然显示错误。

(2)更改方式入下:我们可以将

People stu = new Student();
改成

Student stu = new Student();
或者是把Student类中的成员变量移动到类People中,即可。

0 0