class Parent {
public Parent() {
System.out.println("Parent Default..");
System.out.println("Object type : " + this.getClass().getName());
this.method();
}
private void method() {
System.out.println("private method");
}
}
class Child extends Parent {
public Child() {
System.out.println("Child Default..");
}
public static void main(String[] args) {
new Child();
}
}
When I run this code it prints the class name of "this" = Child but the "this" object is able to call the private method of parent class why?
First of all, when calling new Child()
, since there is not a declared non-argument constructor in Child
class, it will simple call super()
which is invoking the Parent
constructor.
Then, when executing this.getClass().getName()
, here this
stands for a Child
instance, this is why you get "Child" as the result. Remember, Object#getClass()
returns the most specific class the object belongs to. see more from here.
About why this.method()
works. First, because Child
extends Parent
, the Child
instance is also a Parent
instance. The java scope modifier controls where the methods or fields can be accessed. Taking Parent#method()
as the example, the private
modifier indicates that this method can only be accessed (invoked) inside the Parent
class. And this is exactly how you code does. it invokes the method inside the constructor of Parent
class, which compiles the rule. See more about java access control from here