bill bill - 3 months ago 14
Java Question

Calling parent method inside sub classes super constructor

I'm self learning java and am working through some problems in my textbook on inheritance. The question is basically to make a superclass

Person
and to add two more classes
student
and
instructor
, where student has a major and instructor has a salary.

Anyways here is what I have so far

public class Person {
private String name;
private String date;
public Person(String name, String date)
{
this.name = name;
this.date = date;
}
public String getName()
{
return name;
}
public String getDate()
{
return date;
}
public String toString()
{
return "The name of the person is :" + getName() + " And this person was born in " + getDate();
}
}


Student.java

public class Student extends Person {

private String major;

public Student(String major)
{
super(super.getName(),super.getDate()); // ERROR
this.major = major;
}
}


My Thought process

Since every Student has a name and birth date, when I call the super constructor, I can just pass in the methods that return a
Person
's name in my original super class. Obviously, as you can tell this isn't working The solution is just to do

public Student(String name, String birthDate, String major)
{
super(name,birthDate);
this.major = major;
}


I thought I would have saved making two extra variables in the constructor
Student
, by just calling the methods
.getName()
and
.getDate()
, i'm going through this chapter again, but am not really understanding where the issue lies.

TLDR
Whats wrong with the line

super(super.getName(),super.getDate());


Thank you very much

Answer

A class is like a blueprint of how an object would be created.

In your case you have got 2 classes, Person as the base class and then Student which inherits from Person.

When you tries to create an object from the Student class through the constructor method, the compiler will first go and build the Person object but note that at this stage, the base class Person is not built yet until you called super() constructor.

So when you say, I would like to use method from my "yet-to-built baseclass (Person)", since the compiler knows a head of time that this won't work because the parent object (which is accessible from the super keyword) is not there yet until super() returns (finished running). Hence doing parent class.getName() method before the parent has been built is invalid.

Also like what many others say, even if you are able to use the super.getName() method, it won't have any values in it since it is not set with a default value.

Hope this helps, happy to discuss further.

Comments