Reputation: 739
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?
Upvotes: 0
Views: 1501
Reputation: 1259
A parent instance is not created here, you can confirm this using jvisualjvm
in the /bin folder of your jdk installation, the child instance is not created either. Parent constructor is still invoked.
output:
Parent Default..
Object type : com.packagename.Child
private method
Child Default..
Parent constructor can be invoked by child class. While in the constructor of parent, as Krishanthy Mohanachandran has noted above, a private method can be legally invoked.
Upvotes: 0
Reputation: 800
when you extend the class the private methods will not be inherited .but the object of the child class contains object of the parent class so when the superclass constructor is called .you are able to call the superclass private method inside the super class
Upvotes: 2
Reputation: 1971
It is abvious, you can call any private members within the class but not outside the class.
In this case it is legal. In this program first the constrctor of the Parent will be called and you can call private method within the class.
Upvotes: -1
Reputation: 260
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
Upvotes: 1
Reputation: 58848
private
has nothing to do with the actual class of the object. A private
member can be accessed by any code within the same top-level class. (A top-level class is one that's not nested, which is unrelated to inheritance)
method
is defined in Parent
, and the call this.method()
is also in Parent
, so it's allowed.
Upvotes: 0