Private methods in Inheritance

后端 未结 9 1651
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 04:19

Here\'s an interesting code snippet:

public class Superclass {

    public static void main (String[] args){
        Superclass obj = new Subclass();
                


        
相关标签:
9条回答
  • 2020-11-29 04:55

    It works because you are casting to a Superclass from within a method of the Superclass. In that context, Superclass.doSomething is available to the compiler.

    If you were to change your super and subclasses to two different arbitrary classes A and B, not related to the class containing the main method, and try the same code, the compiler would complain about not having access to the method.

    0 讨论(0)
  • 2020-11-29 04:59

    Since the reference type of the object obj is SuperClass, a call to doSomething() tries to access the private method defined in SuperClass itself (private methods cannot be overridden). As doSomething() is accessible within SuperClass, the main method can call doSomething() without giving any error/s.

    Hope this helps! :-)

    0 讨论(0)
  • 2020-11-29 05:01

    When you used this line:

    Superclass obj = new Subclass();
    

    You casted Subclass into a Superclass Object, which uses only the methods of the Superclass and the same data. If you casted it back into a Subclass, you could use the Subclass methods again, like so:

    ((Subclass)obj).doSomething(); #prints "from Subclass"
    
    0 讨论(0)
提交回复
热议问题