简体   繁体   English

与子类和超类的混淆

[英]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? 在上面的示例中,Inner类扩展了Master类,但是我感到困惑的是test.getClass()返回Inner,但是测试不是真的是Master类型吗? Other than the constructor no methods/properties can be used from the Inner class, only what's in the Master class. 除了构造函数外,Inner类不能使用任何方法/属性,只能使用Master类中的方法/属性。 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. 此外,Inner的构造函数实际上设置了Inner专有的属性,但是即使它们使用构造函数,这些属性在某种程度上在测试中也不存在-这似乎不起作用。

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. 测试将使用设置了innerNumber的Inner构造函数,但是test.innerNumber甚至不存在,因为innerNumber与Master类型没有区别。 Also, test.getClass() says it's of the Inner type, not Master. 另外,test.getClass()表示它是内部类型,而不是主类型。

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). Object.getClass()返回对象的动态类型的类对象,而不是静态类型(声明了它的变量或属性的类型)。

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. 因此,无论持有引用的变量类型是什么, new Inner().getClass()返回Inner.classnew Master().getClass()返回Master.class

Question 1: 问题1:

Master test = new Inner();

The above line indicates that get method implementation's from Inner class ( ovveriding ). 上面的代码行表示从Inner类( ovveriding )获取方法的实现。 So Inner classes getClass() method calls. 因此内部类的getClass()方法调用。

Question 2: 问题2:

test.innerNumber 

Inheritance happens from Parent to Child. 继承发生在父母之间。 innerNumber is a property of Inner (child). innerNumberInner (子级)的属性。 Master (Parent) won't get it. Master (父母)不会得到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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