Which methods can a subclass inherit in Java?

后端 未结 6 1443
说谎
说谎 2021-02-09 19:12

Sorry I am a newbie to Java. I am trying to get my head around inheritance and subclass/superclass relationships in Java.

If classA is a subclass of classB, will classA\

相关标签:
6条回答
  • 2021-02-09 19:24

    ClassB's private methods are not visible to ClassA. If you want to give ClassA access to internal methods of ClassB (without those methods becoming part of ClassB's public interface) you should make them protected instead of private.

    0 讨论(0)
  • 2021-02-09 19:28

    ClassA will inherit all of classB's public and protected methods. It will NOT include classB's private methods.

    0 讨论(0)
  • 2021-02-09 19:31

    Private methods are not inherited. Only protected, public and default methods are inherited.

    Class A will provide the methods that are public in both classA and ClassB

    0 讨论(0)
  • 2021-02-09 19:43

    All public and protected methods and variables will be inherited. Any methods with the same signature in the subclass will override the superclass behavior. The subclass will not inherit private methods and variables. Default (a.k.a package visibility level) will be inherited if in the same pacakge and by subclasses.

    0 讨论(0)
  • 2021-02-09 19:43

    Public methods, labeled by public are available to every class. Protected methods, labeled by protected are available to subclasses and friendly classes, which are classes in the same package. Friendly methods, labeled by nothing (i.e. default) are available to friendly classes. Private methods are available only to the class itself.

    Static methods, labeled by static are available to without an object to access them. These are called by ClassName.foo(), SuperClassName.foo() (unnecessary if not overriden, foo() is acceptable), or ClassName.foo() (unnecessary, foo() is acceptable) Dynamic (check vocab???) labeled by nothing (i.e. default) are available only if one has an object of the class. ex: bar.foo(), this.foo() (unnecessary, foo() is acceptable), or super.foo() (unnecessary if not overridden, foo() is acceptable) Overriden methods, annotated by @Override are only available through super.foo

    So in an instance of ClassB, all protected and public members and methods of ClassA will be accessible. In a static call, only static methods are accessible.

    0 讨论(0)
  • 2021-02-09 19:44

    Firstly, the word "inherited" isn't quite the right term. You mean "visible".

    • public and protected are always visible
    • private is not visible
    • default (a.k.a. "package") visibility - ie no specified visibility - is visible only if the subclass is in the same package (as it be would for any class in the same package)
    0 讨论(0)
提交回复
热议问题