Reputation: 5937
My code -
public abstract class Level1Class
{
protected double num = 0.0D;
protected Level1Class(){}
protected Level1Class(double num){this.num = num;}
protected abstract methods A, B, C...etc //pseudocode !
}
public class Level2Class extends Level1Class
{
//NO CONSTRUCTORS HERE
//BUT, only implementation of methods A,B, C
}
public class Tester
{
Level2Class l2c = new Level2Class(10.0D); //This causes the compiler error !
}
Can someone tell me why I get this error. I know it will go if I create the necessary constructor in Level2Class. But, I want to know the reason.
Upvotes: 1
Views: 571
Reputation: 20751
Create a constructor with a double parameter in Level2Class class
public class Level2Class extends Level1Class
{
Level2Class (double val)
{
// body of the constructor
}
}
Upvotes: 2
Reputation: 1197
In Java,whenever a class is extended,only the public and protected methods are inherited,but not the constructors.
Upvotes: 1
Reputation: 3658
constructor in java not polymorphic, when you call new Level2Class(10.0D)
program can't find Level2Class(double)
it sees Level2Class()
which is default constructor in this case.
simply saying after compiling you code would be like:
Level2Class {
Level2Class() { super(); }
}
so you have to declare constructor Level2Class(double) { super(double) }
in order this to work
Upvotes: 1
Reputation: 57316
The main reason for the behaviour you describe is that in Java constructors are not inherited. When you create a class, you have two choices:
Do not specify any constructors at all (as in your example). In this case the compiler will automatically add a default constructor (with no parameters).
Create specific constructors (with parameters or without). In this case only the constructors you define will exist in the class, the compiler will not add a default one.
In your example, you are not defining any constructors in class Level2Class
, therefore the compiler adds the default constructor with no parameters. Constructor with parameters double
doesn't exist in the compiled class and hence your error Constructor undefined.
Upvotes: 5
Reputation: 41210
Level2Class
have a only default constructor which would be implemented by compiler. Level2Class
does not have constructor which takes double as parameter.
Level2Class l2c = new Level2Class(10.0D);
This will try to figure out double constructor in Level2Class
class which is not available because constructor are not inherited.
Upvotes: 3