java我不理解“this”与超类一起使用
我有两个类和一个接口,如下所示。 快速总结:接口Winterface、大类、扩展大类并实现Winterface的小类
public interface Winterface {}
public class Big {
public int hello = 88;
public Big() {}
public void theMethod() {
System.out.println ("Big was here: " + (this instanceof Winterface) + ", " + this.hello);
}
}
public class Little extends Big implements Winterface{
private boolean hello = true;
public Little(){}
public void theMethod() {
super.theMethod();
System.out.println("Little was here: " + hello);
}
public static void main(String [] args) {
Little l = new Little();
l.theMethod();
}
}
当我执行main时,我得到以下输出
Big在这里:没错,88 这里没有什么:真的
我的问题是,你怎么能
1)(此Winterface实例)返回true,但
2)这个。你好,88岁吗? 如果是这样的话。hello=88,然后this=Big,这不是Winterface的实例
我不明白这怎么可能,提前谢谢
编辑:谢谢大家,我现在明白了“this”指的是little,它是一个大而复杂的词。因为该方法被称为super。method(),可用变量“hello”是Big中的变量,尽管“this”指的是little
# 1 楼答案
l
是Little
,但是Little
是Big
并且也实现了Winterface
的行为super
是对父类的调用,因此使用父类的hello
成员(即Big
)您所做的不是
this.hello
,而是super.theMethod()
使用父级的类成员变量hello
更新:
super.theMethod()
调用父类中相应的方法。在父类中,您可以访问父类的字段(也属于派生类,因为Little
也是Big
)。因此,此时的this.hello
正在访问属于父类的代码部分您可以想象
Little
的内存打印如下:因此
Little
具有父级的所有成员变量,即Big
,当代码在super.theMethod()
内运行时,它在Big
的“代码区”内运行正如彼得在他的回答中所说的那样,方法不支持多摩门教,我希望这种过于简单化的描述有助于理解这一点
# 2 楼答案
this
只能是一个类。但是this.hello
是该类可以访问的字段因为
this
只能是一个类,所以它是一个Little
,它有一个父Big
,当你在其父中调用一个只能看到hello
的方法时,它实现了Winterface
也就是说,Java支持方法的多态性,但不支持字段
# 3 楼答案
这里发生的事情是,当您在{}中定义变量{}时,您没有覆盖{}中的变量{},而是在{}中定义一个新变量{},该变量在{}中隐藏变量{}。因此,在
Big
的范围内,hello
将指88的整数值,在Little
的范围内,hello
将指true。这些变量都包含在对象中,唯一的区别是引用它们的范围正如其他人所说,
instanceof
是一个比较对象的运行时类型(由this.getClass()
返回的内容)的操作符。在Big
中时,即使对象中的变量范围将引用Big
,this
仍然是运行时类型Little
,这就是为什么它是Winterface
的实例# 4 楼答案
这是因为
this instanceof ...
检查不使用静态(即编译时)类型(即Big
),而是使用对象的(this
)动态运行时类型(即this.getClass()
),在您的示例中是Little
。如果它使用静态类型,那么操作符将毫无意义,因为我们会:静态地,在编译时。
instanceof
运算符的目的是启用运行时类型测试,例如:请注意,此技术只能少量使用
# 5 楼答案
你的变量是大和小的实例。这是Little的直接实例,但由于Little继承自Big,因此instanceof操作符也将为Big返回true
你的另一个误解(我假设)是“方法查找”是如何工作的。当您调用该方法时,它会选择Little对该方法的实现。当你叫super的时候。不过,在该方法中,您明确地说了“调用Big的此方法版本”,然后在该方法中使用Big的hello变量,而不是Little的hello变量