gudii9
asked on
super sub class constructor
Constructors are not inherited:
The sub class cannot inherit constructors from its super class. Consider the following example:
1
2
3
4
5
6
7
8
9
10
11
public class Super {
protected String text;
public Super(String text) {
this.text = text;
}
}
public class Sub extends Super {
}
We can create a new instance of Super like this:
1
Super super = new Super(“Hello”); //OK
But we cannot do the same for the Sub class:
1
Sub sub = new Sub(“Hello”); //Compile error, since constructor is not inherited
The solution is to write a constructor for the sub class and call the super’s constructor, for example:
1
2
3
4
5
6
public class Sub extends Super {
public Sub(String text) {
super(text);
}
}
https://www.codejava.net/java-core/the-java-language/12-rules-and-examples-about-inheritance-in-java
i wrote as below
package SuperSub;
public class Super {
protected String text;
public Super(String text) {
this.text = text;
}
}
package SuperSub;
public class Sub extends Super {
//Super super = new Super(“Hello”);
}
i am getting error in line 2 of Sub class
Implicit super constructor Super() is undefined for default constructor. Must define an explicit constructor
package SuperSub;
public class Sub extends Super {
public Sub(String text) {
super(text);
// TODO Auto-generated constructor stub
}
//Super super = new Super(“Hello”);
}
above is fine though not sure why i cannot just have Sub empty class?Please advise
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.