Reputation:
I have the following problem: implicit super constructor is undefined must invoke another constructor java
. I have two classes one which inherits and calls the super - Method.
Person-Class:
public class Person {
private String firstName;
private String name;
private Date birthday;
private Gender gender = Gender.Unknown;
Person(String fn, String n, Date d, Gender g){
firstName = fn;
name = n;
birthday = d;
gender = g;
}
Person(Person p){
firstName = p.firstName;
name = p.name;
birthday = new Date(p.birthday);
gender = p.gender;
}
Person(String fn, String n){
firstName = fn;
name = n;
}
And the second Class:
public class Student extends Person implements Noten {
private int nr;
private String st;
Student(int m, String s){
this.nr= m;
this.st= s;
}
Student(Person p) {
super(p);
// TODO Auto-generated constructor stub
}
Why upon extending to class Person, Student class must implement Stundet(Person p) - Method?
One Solution: Add a Person() - Method to the Person-Class
:
Person(){
System.out,println("Hello World"};
Still doesn't work.
First Question: Why does the super(p) - Method doesn't work?
Second Question: How do i make it work even without adding a Person()
- with no Parameters to the Person-Class
?
Third Question: Why didn't adding Person()
- work?
Upvotes: 0
Views: 220
Reputation: 649
To add to what others have said, in order to construct an instance of your Student class, your class has to call some constructor in Person. Otherwise nothing in the parent class would be initialized, which would make extending Person useless.
Since in your first Student constructor you are not explicitly calling a person constructor, java tries to find a no-argument Person() constructor, which you don't have defined. Not finding it, you get this compilation error that you are seeing.
This is a very basic java question, so I'm assuming you are very new to java. I highly recommend reading a beginner's java book or online (in-depth) tutorial to get some of the basics down before you start coding or to refer to while you are practicing your coding. You will spend a lot of time spinning your wheels (or waiting for answers online) without those basics.
Upvotes: 0
Reputation: 159086
First Question: Why does the super(p) - Method doesn't work?
It works fine, in that second Student
constructor.
Second Question: How do i make it work even without adding a Person() - with no Parameters to the Person-Class?
You need to call one of the Person
constructors using the super(...)
syntax in that first Student
constructor, because you must provide at least a firstName
and a name
.
Third Question: Why didn't adding Person() - work?
Added a no-argument constructor to Person
does work, since the compiler can now implicitly call that Person
constructor in the first Student
constructor.
Upvotes: 1