Reputation: 143
Below is a simple example. I have two abstract classes, A
and B
, one concrete class, C
, which includes the abstract method.
When I create a new C
, I expected to see the constructors of A
and B
being called. Any idea why they are not called?
//Q.java
class Q {
abstract class A {
A() {
System.out.println("in A");
}
public abstract void sayHi();
}
abstract class B extends A {
B() {
super();
System.out.println("in B");
}
}
class C {
C() {
super();
System.out.println("in C");
}
public void sayHi() {
System.out.println("Hi!");
}
}
Q() {
C Ccc = new C();
}
public static void main(String[] args) {
Q z = new Q();
}
}
Upvotes: 0
Views: 2649
Reputation: 16335
C
and B
are not related in any way. super class of C is java.lang.Object
by default
C
should extend B
like
class C extends B{ .. }
In such a case, it will call the super class constructors.
Also, you do not need to call super()
explicitly as it is implicitly there.
Upvotes: 1
Reputation: 1378
See, we have the super class Object which all classes extend implicitly. so if we have
public class A{}
then it is equivalent to writing
public class A extends Object{}
.
But if you want to extend another class of your own then you have to explicitly mention it as
public class B extends A{}
else java will treat Object as your super class. (NOTE: even it this case Object is a super class to 'B' but this is because it is a super class to 'A' and hence 'B'). So if you don't explicitly mention the 'B extends A' then class B will have Object as its only super class.
More over you dont need mention super() in the sub class constructor. This too is called implicitly.
Upvotes: 2
Reputation: 3390
Just make:
class c extends b{
It will work now.. you have not extended b in c..
Upvotes: 2
Reputation: 13872
you should extends the abstract classes from class c
.
class c extends b {
Without extending b
explicitely, it is equivalent to
class c extends Object {
and, hence call to super
invokes Object
constructor.
Upvotes: 2
Reputation: 24316
Because the super class of c
is Object
Further class names start with upper case letters A,B,C,etc
If you want to see both a
and b
invoked do this:
class c extends b
Upvotes: 6
Reputation: 16351
Your class c
doesn't extend class b
or a
, so it can't call their constructors using super()
and calls Object
constructor instead.
Try this :
class c extends b {
public c(){
super();
//...
}
}
Upvotes: 3