Reputation: 3201
Please help me to understand how inheritance works.
If I have two classes, parent and child. When I create an instance of child is parent class instance constructed as well or not?
My code of Parent
class.
public class Parent {
private char s;
@Override
public int hashCode() {
return s;
}
}
And Child
public class Child extends Parent {
private int i;
public Child(int i) {
super();
this.i = i;
}
@Override
public int hashCode() {
return i;
}
}
And finally the test
public class Main {
public static void main(String[] args) {
Child child = new Child(100);
System.out.println(child.hashCode());
System.out.println(child.getClass().getSuperclass().hashCode());
}
}
In output I get
100
2000502626
So the hashes of objects are different. It means that when I create instance of Child
it is also created instance of Parent
. Am I right?
Upvotes: 0
Views: 115
Reputation: 36304
Actually, there will be just one child object created. Since every child is a parent, the parent constructor will be invoked. if you print this
in both child as well as parent instance methods, it will print the same (child object)
check - this question
Upvotes: 1
Reputation: 1382
When you create a Child object a Parent constructor is invoked as well, because a Child is a Parent.
But when you do this:
System.out.println(child.getClass().getSuperclass().hashCode());
you're not invoking Parents
instance hashode. You are invoking hashCode() of the instance of the Class
object.
See what child.getClass().getSuperclass()
returns. It returns an instance of type Class
not of type Parent/Child.
You cannot invoke Parents
instance methods using child.getClass().getSuperClass() - that doesn't return the instance of a type, but an object representing this type.
Try doing this in child method:
@Override
public int hashCode() {
System.out.println("In child hashCode: " + i);
System.out.println("Parents hashCode: " + super.hashCode());
return i;
}
This will return 100 and 0, as Parents
s
hasn't been initialized.
Upvotes: 3
Reputation: 9300
Yes. Both parent and child object are created. The child class constructor calls the parent(super) class constructor first, then only other functions of the child class are performed. As you can see from your own code two different values getting printed.
Upvotes: -1
Reputation: 2394
If I have two classes, parent and child, When I create an instance of child is parent class instance constructed as well or not?
Yes. It works through Constructor. When you call constructor of your child class to create object, it first calls its parent class contructor and hence creates object of parent class
Upvotes: 0
Reputation: 195059
Your question has nothing to do with inheritance.
the 100
you get from child
instance's hashcode()
method, as you expected.
The 2000502626
was from Parent.class
, not Parent object
.
Parent.class
has type java.lang.Class
parent object
has type Parent
Upvotes: 10