I was wondering if it was possible to do the following with a Class, that extends another class in Java, if so. How?:
public class HelloWorld {
public HelloWorld() {
A aClass = new A(22);
}
}
public class A extends B {
public A() {
System.out.println(number);
}
}
public class B {
public int number;
public B(int number) {
this.number = number;
}
}
Your A
constructor needs to chain to a B
constructor using super
. At the moment the only constructor in B
takes an int
parameters, so you need to specify one, e.g.
public A(int x) {
super(x); // Calls the B(number) constructor
System.out.println(number);
}
Note that I've added the x
parameter into A
, because of the way you're calling it in HelloWorld
. You don't have to have the same parameters though. For example:
public A() {
super(10);
System.out.println(number); // Will print 10
}
Then call it with:
A a = new A();
Every subclass constructor either chains to another constructor within the same class (using this
) or to a constructor in the superclass (using super
or implicitly) as the first statement in the constructor body. If the chaining is implicit, it's always equivalent to specifying super();
, i.e. invoking a parameterless superclass constructor.
See section 8.8.7 of the JLS for more details.
See more on this question at Stackoverflow