1

I have some problem when read the blog. The following confuse me for a while.

Parent:

class Insect {
private int size;
private String color;

public Insect(int size, String color) {
    this.size = size;
    this.color = color;
}

//getter, setter

public void move() {
    System.out.println("Move");
}

public void attack() {
    move(); //assuming an insect needs to move before attacking
    System.out.println("Attack");
}
}

Child:

class Bee extends Insect {
public Bee(int size, String color) {
    super(size, color);
}

public void move() {
    System.out.println("Fly");
}

public void attack() {
    move();
    super.attack();
}

main :

public static void main(String[] args) {
    Insect i = new Bee(1, "red");
    i.attack();
}

Why the result is "fly fly attack" and not "fly move attack"? Calling super.attack() ,the move() method from Insect class should be invoked, shouldn't?

WhiteBanana
  • 349
  • 4
  • 20
  • No, it is using the "deepest" implementation of the method, since this is override in `Bee`, even by calling it from `super.attack()` won't change that. – AxelH Dec 16 '16 at 14:37
  • oh~got it. thank you all – WhiteBanana Dec 16 '16 at 14:53
  • @WhiteBanana Another way to understand this would be to precede all the open method calls in `Insect` and `Bee` with `this` keyword. The `this` reference always points to the current instance. – Chetan Kinger Dec 16 '16 at 14:57

0 Answers0