Java inheritance - please explain

inheritance, java

Solution

Because you defined sayIt() to be private, class B cannot override it. As such, you have two definitions of sayIt() rather than just one that is overriden by a subclass.

While inside a section of class A code, it will always call the version from class A, even if the class B version was protected or public. This is because class A only knows about the version from class A since the class B version is not an override, but a completely different method that just so happens to share the same name.

While inside of a section of class B code, it will always call the version from class B since the class A version is marked private. As noted by others, if you change the definition to protected or public, it will be visible to class B and it will do what you want.

Note that if you were to use the default (package) visibility, the scoping rules would get to be very complex and the actual results would vary depending on which subclasses are in the same package and which are in different ones.

Problem

``` class A { public void talk(){ this.sayIt(); } private void sayIt(){ System.out.println("class A says..."); } } class B extends A { private void sayIt(){ System.out.println("class B says..."); } } ``` Test class, main method: ``` B b = new B(); b.talk() //output class A says... ``` I cannot get this since: Class B inherits from class A, the public member and cannot see/inherit the private function. So in class B, we could call talk(). //since it is inherited by the parent class. Now, in the talk() method, there is a call to sayIt() since sayIt() is defined in class B, I would expect a call to B.sayIt() to be made when this.sayIt() is executed. Doesn't "this" refer to the class B? Please Explain.

Original source