I am trying to really understand how inheritance and the super keyword work.
I have the following 4 classes:
People class:
public class People {
public static void main(String[] args) {
Person people[] = new Person[4];
people[0] = new Teacher("Anna-Belle", 37, 6);
people[1] = new Teacher("John McGil", 43, 12);
people[2] = new Student("Jason Blue", 25, 17);
people[3] = new Student("Alice Grad", 22, 34);
// let's print student's credits
// and teacher's courses taught
for (int i=0; i < people.length; i++) {
Person p = people[i];
if (p instanceof Teacher) {
Teacher t = (Teacher) p;
System.out.println("Teacher #" + t);
} else if (p instanceof Student) {
Student s = (Student) p;
System.out.println("Student #" + s);
} else { };
}
}
}
Person class:
class Person {
String name;
int age;
Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String toString() {
return " " + super.toString() + " (Person): " + name + ", " + age;
}
Teacher class:
class Teacher extends Person {
Teacher(String n, int a, int c)
{
super(n,a);
coursesTaught = c;
}
public String toString() {
return super.toString()
+ ", (Teacher): " + coursesTaught;
}
int coursesTaught;
}
Student class:
class Student extends Person {
Student(String n, int a, int c)
{
super(n,a);
creditsCompleted = c;
}
public String toString() {
return super.toString()
+ ", (Student): " + creditsCompleted;
}
int creditsCompleted;
}
What I don’t understand is how the super keyword works I guess. for instance how come the super.toString() in the teacher class knows what to take and convert to a string??
Actually thinking about it, I understand what super does. It says to go to the up a level to the superclass. I guess I am confused as to what happens when these 2 are combined? Any help is appreciated
You are right:
supergoes up one level and invokes the toString() method on the parent class.What might not be obvious, if you are new to Java, is that every class inherits from
Object. Every class that does not explicitly extend something, implicitly extendsObject. So, in effect, yourPersonclass looks like this (BTW, this still compiles):For a more visual representation go to your
Teacherclass in Eclipse and pressCtrl+TTherefore, when you call
toString()on aTeacherinstance,toString()is invoked onPerson. There anothersuper.toString()call is made. The direct parent ofPersonisObjectthus the defaulttoString()on theObjectclass is invoked, which looks like this:That is where the first part of your output comes from. The part before the @, is the runtime type of the instance. The hex string after the @ is a hash representing the object instance, which is usually derived from the memory location:
Teacher #Teacher@5d0385c1(Person): Anna-Belle, 37, (Teacher): 6It is the runtime type that determines which method will be called. E.g.
will print this:
Even though the compile time type is
Personat runtime thetoString()onTeacheris invoked.