The same rule applies to constructors of a superclass. If a class has a superclass and that superclass has at least one constructor, then a constructor of the superclass must be called when an object is created. It is generally the responsibility of the subclass constructor to make a call to a superclass constructor. If the subclass constructor doesn't call the superclass constructor and the superclass has a constructor with no parameters, Java will call that superclass constructor automatically. But, if all the superclass constructors require parameters, java won't be able to call one of them--in that case, the subclass constructor is required to make a call.
Here is an example:
Code:
class animal
{
animal()
{
/* Java code here */
}
}
class cat extends animal
{
cat()
{
super();
/* Java code here */
}
}
In this example, the subclass constructor is calling the superclass constructor. (Notice how it uses the keyword super to do that.) In this case, the call to super isn't required. Since the superclass constructor has no parameters, Java will call the superclass constructor if the subclass constructor doesn't.
Here is another example:
Code:
class animal
{
animal(int age)
{
/* Java code here */
}
class cat extends animal
{
cat()
{
super(5);
/* Java code here */
}
}
In this example, there are no superclass constructors without parameters. That means the subclass constructor is required to call the superclass constructor.
When a subclass constructor calls a superclass constnxctor, it must be done at the very beginning of the subclass constructor No other processing can be done first.
Bookmarks