WesleyHsiung WesleyHsiung - 1 month ago 5
Java Question

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.

Answer
  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)

Comments