继承概念:继承会使子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法。
Java官方文档中有这么几句话:
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent.
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
从上面翻译的意思如下:
- 子类继承父类所有public和protected成员,如果子类和父类在同一个包下,子类还将继承父类的package-private 成员。
- 构造函数不是类的成员,它们是不能被继承的,但是可以从子类调用超类的构造函数。
- 子类不继承父类的private成员,但是可以通过父类的public或protected方法访问父类的private属性。
个人理解:
- 之前认为的是子类能够继承父类的所有成员,包括public、private、default和protected成员。不过这里的 “继承” 可能用 “拥有” 这个词更好。子类拥有父类的所有成员。
- 父类的private成员,子类是无法直接访问的。父类的private属性可以通过public或protected修饰的方法访问。
- 在 Java 中,子类是不能继承父类的private成员的。一个子类只能继承其父类的可访问的成员(public和protected),并且该子类没有覆盖或者隐藏父类中的那些可访问成员。
- 子类的成员包括子类中所声明的属性和方法,再加上从其父类继承而来的属性和方法。
- 父类中静态成员可以被继承,如果子类有和父类相同的静态成员,父类静态成员不会被重写(override)而是被隐藏。
- 从内存的角度来说,子类拥有父类的所有成员。 子类不继承父类中的private成员,但是在父类中的private成员仍然是子类类型对象的一部分。在实例化的过程中,JVM 需要为对象的类及其父类中所有定义的属性分配空间,包括父类中声明的private成员。
总结:
子类继承父类的public和protected成员(可直接访问成员),不继承private成员(不可直接访问)。但是,子类的对象拥有父类的所有成员。
另外,类中不能被继承的有:
- 构造函数
- private成员
- 赋值运算符重载函数(C++中)等