Understanding Inheritance and Overriding

In fact, my question was already the answer, but I can not understand it correctly. Here is the code snippet:

public class Superclass {

   public static void main (String[] args){
      Superclass obj = new Subclass();
      obj.doSomething(); #prints "from Superclass"
   }

   private void doSomething(){System.out.println("from Superclass");}
}

class Subclass extends Superclass {

    private void doSomething(){System.out.println("from Subclass");}

}

He prints: "from the superclass"

Since the reference type of the obj object is SuperClass, the doSomething () call attempts to access the private method defined in SuperClass (private methods cannot be overridden). As doSomething () is available in SuperClass, the main method can call doSomething () without any errors / s.

As far as I can imagine, a method call works this way: (maybe I'm completely wrong about that):

, , Java . ( , " " )

doSomething() , , Java , , SuperClass, SubClass. SuperClass?

, ?

, - , .

+4
3

, , , . .

N.B: ; , , , , . ..

+2

"doSomething" , . , .

, java. , ?

0

.

, ( - , ).

private , "" . , protected : , childs . .

0

Source: https://habr.com/ru/post/1609857/


All Articles