Reputation: 901
Master test = new Inner();
System.out.println(test.getClass());
In the above example the Inner class extends the Master class, but what I'm confused about is that test.getClass() returns Inner, but isn't test really of the type Master? Other than the constructor no methods/properties can be used from the Inner class, only what's in the Master class. Furthermore the constructor for Inner actually sets properties exclusive to Inner, but somehow these properties don't exist in test even though it uses the constructor -- which doesn't seem like it should work.
For example if define the classes as:
public class Master {
public int number = 0;
public Master() {
number = 9;
}
}
public class Inner extends Master {
public int innerNumber = 0;
public Inner() {
number = 1;
innerNumber = 2;
}
}
test will use Inner's constructor which sets innerNumber, but test.innerNumber doesn't even exist because innerNumber isn't apart of the Master type. Also, test.getClass() says it's of the Inner type, not Master.
Upvotes: 0
Views: 81
Reputation: 122026
Question 1:
Master test = new Inner();
The above line indicates that get method implementation's from Inner
class (ovveriding). So Inner classes getClass()
method calls.
Question 2:
test.innerNumber
Inheritance happens from Parent to Child. innerNumber
is a property of Inner
(child). Master
(Parent) won't get it.
Upvotes: 0
Reputation: 418585
Object.getClass()
returns the class object of the dynamic type of the object, not the static type (the type of the variable or attribute you declared it).
Hence new Inner().getClass()
returns Inner.class
, new Master().getClass()
returns Master.class
no matter what the type of the variable is that holds the reference.
Upvotes: 3