-1

This is the superclass:Glyph

public class Glyph {
    void draw() {
        System.out.println("Glyph.draw(");
    }
    Glyph() {
        System.out.println("Glyph() before draw()");
        draw();
        System.out.println("Glyph() after draw()");
    }
}

This is the subclass RoundGlyph

class RoundGlyph extends Glyph {
    int radius = 1;
    RoundGlyph(int r) {
        super();
        radius = r;
        System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
    }

    void draw() {
        System.out.println("RoundGlyph.draw(), radius = " + radius);
    }
}

We use this class to test.

public class PolyConstructors {
    public static void main(String[] args) {
        new RoundGlyph(5);
    }
}

Output:

Glyph() before draw()
 RoundGlyph.draw(), radius = 0
 Glyph() after draw()
 RoundGlyph.RoundGlyph(), radius = 5

Why the program execute the method draw() in class RoundGlyph when it is executing the super()?

and print

RoundGlyph.draw(), radius = 0
user207421
  • 305,947
  • 44
  • 307
  • 483
Andrew
  • 3
  • 1
  • 3
    Read up on polymorphism and overriding methods. In any case as your code shows, this is also why you should **not** call instance methods from a constructor. – Mark Rotteveel Apr 21 '18 at 11:15

1 Answers1

0

It's a polymorphism! when you call method from parent, the method in child will invoke if override exist. if you would like invoke the method of parent you must do like this:

class RoundGlyph extends Glyph {
   int radius = 1;
   RoundGlyph(int r) {
    super();
    radius = r;
    System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
  }
@Override
void draw() {
   super.draw();//go draw in parent first
   System.out.println("RoundGlyph.draw(), radius = " + radius);
 }
}

or you must explicit method call in parent like this:

public class Glyph {
 void draw() {
  System.out.println("Glyph.draw(");
 }
 Glyph() {
  System.out.println("Glyph() before draw()");
  Glyph.draw();//explicit calling
  System.out.println("Glyph() after draw()");
 }
}
Iman.B
  • 68
  • 9