英文:
Use keyword this/super in base class gives subclass name
问题
不明白关键词this和super在这些情况下的作用方式。这里有两个继承的例子。
主方法是共通的。
public static void main(String[] args) {
SeaCreature dolphin = new Dolphin();
dolphin.swim(); // Dolphin正在游泳 - 在两种情况下都是这样
}
SeaCreature类是共通的。
class SeaCreature {
public void swim() {
System.out.println(this.getClass().getSimpleName() + "正在游泳");
}
}
第一个情况下的Dolphin类。在这种情况下,我期望swim()方法中的this给出的是SeaCreature对象,而不是Dolphin。
class Dolphin extends SeaCreature {
}
第二个情况下的Dolphin类。在这种情况下,我期望swim()方法中的super给出的是SeaCreature对象,而不是Dolphin。
class Dolphin extends SeaCreature {
@Override
public void swim() {
System.out.println(super.getClass().getSimpleName() + "正在游泳");
}
}
然而在两种情况下,结果都是"Dolphin正在游泳"。这是怎么回事呢?
英文:
Just do not understand how keywords this and super works in these cases. Here are 2 inheritance examples.
Main method is common.
public static void main(String[] args) {
SeaCreature dolphin = new Dolphin();
dolphin.swim(); // Dolphin is swimming - in both cases
}
SeaCreature class is common.
class SeaCreature {
public void swim() {
System.out.println(this.getClass().getSimpleName() + " is swimming");
}
}
Dolphin class for the first case. In this case I would expect that this in swim() method gives SeaCreature object not Dolphin.
class Dolphin extends SeaCreature {
}
Dolphin class for second case. In this case I would expect that super in swim() method gives SeaCreature object not Dolphin.
class Dolphin extends SeaCreature {
@Override
public void swim() {
System.out.println(super.getClass().getSimpleName() + " is swimming");
}
}
However in both cases the result is "Dolphin is swimming". How this works?
答案1
得分: 3
混淆可能来自于getClass()
方法,该方法返回对象的运行时类,这意味着您将会得到您实例化的类,而不是父类,即使方法调用发生在父类中。
我建议硬编码一个字符串"Dolphin"
或"SeaCreature"
,并使用它们,这可能会帮助您更好地可视化调用。
链接:https://beginnersbook.com/2013/03/polymorphism-in-java/
英文:
The confusion is probably coming from the getClass()
method, which returns the runtime class of the object, which means you'll get back the class you instantiated, not a parent class, even if the method call takes place in a parent class.
I'd recommend hard-coding a string "Dolphin"
or "SeaCreature"
, and using those, which will probably help you visualize the calls better.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论