Reputation: 13
Suppose there are three classes A, B and C. C extends B and B extends A. Can we call class A constructor directly without calling class B constructor in sub class C?
Upvotes: 1
Views: 711
Reputation: 2652
Not directly .. but something like this can be done:
public class A {
A(){
....
}
}
public class B extends A {
B(){
super();
....
}
}
public class C extends B {
C(){
super();
....
}
}
// In main()
C c = new C(); // This will eventually call A's constructor
Upvotes: 0
Reputation: 6114
No you can't, although the constructor of child class starts executing first(when you create its object) but there's always a no-arg constructor call to super in the constructor of the child(unless you manually call super with arguments) and so on. Following this hierarchy the constructor of the top most parent class although starts its execution at last, but finishes first!
Upvotes: 0
Reputation: 1841
I don't think that is possible. Anyways, if C does not relate to B, but to A, why does C extend B in the first place?
You could also try and create some protected method in A that could be called from both A's and C's constructors.
If you could try and describe what you're trying to model, maybe some alternative hierarchy would be more suitable.
Upvotes: 1
Reputation: 181114
No. The constructor of a subclass will explicitly or implicitly invoke one of the constructors of its superclass to initialize itself. Constructors of other classes cannot be invoked (except to initialize different objects) whatever those classes' relationship to the class being initialized may be.
Upvotes: 3