1

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?

Kirill Ch
  • 5,496
  • 4
  • 44
  • 65

1 Answers1

3

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/

the_storyteller
  • 2,335
  • 1
  • 26
  • 37
  • 2
    Alternatively `Dolphin.class.getSimpleName()` and `SeaCreature.class.getSimpleName()`, refactoring tools may find it easier to rename the classes that way. – Mario Ishac Aug 25 '20 at 18:53