简体   繁体   中英

Confusion with subclasses and superclasses

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM