jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes default inclusion of call to super's cosntructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "default inclusion of call to super Watch "default inclusion of call to super New topic
Author

default inclusion of call to super's cosntructor

Imtiaz Nizami
Greenhorn

Joined: May 19, 2007
Posts: 12
We know that if we implement a constructor for a Class, Java do not create the default one. We also know that if a subclass constructor is called, constructor chaining happens and the superclass's constructor is called.=

Say we have Class A and Class B. B is the subclass of A.

public class A {
int size;
public A (int mySize) {
size = mySize;
}
}

public class B extends A {
public B {
}
}

If B does not explicitly calls super with the correct parameters, how can Java compiler put in a super call which is NOT no-arg - we know that no no-arg constructors exist for Class A.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

Your class B won't compile, for exactly the reason you give. B must explicitly call A's constructor and provide the argument.


[Jess in Action][AskingGoodQuestions]
Imtiaz Nizami
Greenhorn

Joined: May 19, 2007
Posts: 12
Thank you. I did try compiling it myself but wanted to make sure with more experienced Java programmers.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

A simple rule with constructors is that if your code compiles, then a constructor is going to be called at each level of the class hierarchy. A constructor will be called at the level of the concrete class that you are instantiating and then at each the level of every class that is inherited -- even in abstract classes (but not in interfaces).

There is a way to prevent a constructor from being called and that is to create a private constructor, but if you don't call the private constructor, the class cannot be instantiated at all (such as the Math class).

Kaydell
 
 
subject: default inclusion of call to super's cosntructor