WesleyHsiung
WesleyHsiung

Reputation: 461

java call method in constructor and abstract class?

public class NewSeqTest {
  public static void main(String[] args) {
    new S();
    new Derived(100);
  }
}


class P {
  String s = "parent";
  public P() {
    test();
  }
  public void test() { //test 1
    System.out.println(s + "  parent");
  }
}

class S extends P {
  String s = "son";
  public S() {
    test();
  }
  @Override
  public void test() { //test 2
    System.out.println(s + "  son");
  }
}

abstract class Base {
  public Base() {
    print();
  }
  abstract public void print();
}

class Derived extends Base {
  private int x = 3;
  public Derived(int x) {
    this.x = x;
  }
  @Override
  public void print() {
    System.out.println(x);
  }
}

//output is

     null  son

     son  son

     0

my question is
1. why P constructor print " null son"; I think is "null parent" ?

2 why can abstract class Base execute abstract method print() in constructor?

sorry for the code format, I do not know how to use it correctly.

Upvotes: 1

Views: 99

Answers (2)

c0der
c0der

Reputation: 18792

  1. Executing new S(); causes P constructor to run test(). It executes the overridden test() in S which prints s. It uses s in S which has not been initialized because the constructor of S is executed after the constructor of P.
    2.The same answer as to 1. Overridden print() is executed but xhas not been initialized yet.


btw: try to use a debugger and run the program step by step to follow the execution path.

Upvotes: 0

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31279

  1. You've overriden the method test in your subclass S and you're constructing an object of type S. So in the superclass constructor, when test() is invoked, it invokes the overriden version of test() from the subclass S. That's the point of overriding.

  2. Same as 1. The method print is not abstract in class Derived, and you're constructing in instance of Derived, not of Base. (It is illegal to say new Base() for the reason that you mentioned: you can't invoke an abstract method)

Upvotes: 2

Related Questions