java继承

继承概念:继承会使子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法。
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++中)等
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值