在基类中使用关键字this/super将给出子类名称。

huangapple go评论66阅读模式
英文:

Use keyword this/super in base class gives subclass name

问题

不明白关键词thissuper在这些情况下的作用方式。这里有两个继承的例子。
主方法是共通的。

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.

https://beginnersbook.com/2013/03/polymorphism-in-java/

huangapple
  • 本文由 发表于 2020年8月26日 02:31:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63585082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定