If I had following question on java theoretical test, what would be the right answer?
The question/task:
Create a Circle class inheriting from the Shape class and call the Shape class constructor in its constructor. Shape class:
public class Shape {
private int size;
}
Choose the correct answer:
A:
class Circle extends Shape{
Circle(){
super();
}
}
B:
"You can't call constructor of Shape class as it doesn't exist"
Some say that the right answer is B, but I don't understand why it can't be A? Won't Java create default constructor and call it anyway?
According to the official Java Language Specification (JLS), section 8.8.9:
If a class contains no constructor declarations, then a default constructor is implicitly declared.
Reading through that section shows that when Shape
is compiled, it gets a constructor as if defined by
public Shape() {}
It is public
because Shape
is public and implicitly calls super();
because it is empty.
So clearly you are correct that option A is the answer.
But what about option B? As it happens, the very next section of the JLS (section 8.8.10) deals exactly with how to create a non-instantiatable class:
A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, to prevent the creation of a default constructor, and by declaring all constructors to be
private
(§6.6.1).
In practice, if you manually declared a private
empty constructor to Shape
, you would not be able to extend it, exactly because the call to super()
in Circle
would not resolve:
private Shape() {}