Reputation: 213
I've been playing around with Inheritance and Polymorphism. The print out of the code below is: Student 1 Person 1 Undergrad 2. So I have two questions:
Why does Java automatically insert a .this when I call method2() in the student class? What if instead of the original print out, I wanted to print out Student 1 Person 1 Student 2. How would I explicitly call method2 of the Student class?
I have 3 classes, the Person class:
public class Person {
public static void main(String[] args) {
Person u = new Undergrad();
u.method1();
}
public void method1() {
System.out.print("Person 1 ");
}
public void method2(){
System.out.print("Person 2 ");
}
}
The student class
public class Student extends Person {
public void method1(){
System.out.print("Student 1 ");
super.method1();
method2();
}
public void method2(){
System.out.print("Student 2");
}
}
And the Undergrad class:
public class Undergrad extends Student{
public void method2(){
System.out.print("Undergrad 2 ");
}
}
Upvotes: 0
Views: 190
Reputation: 33
Try to look into the all keywords such as public, final, private, static. Then there are the topics of "method hiding" and "method overriding". Also look into the '@override annotation'. Try to understand how you can cast classes. Besides the other answers in this topic, in your example you can also do:
Student u = new Undergrad();
because any instance of Undergrad is also a Student. However now you have access to the methods of Student. So I'd suggest making method2 inside Student private so u.method2() prints "Student 2".
Upvotes: 0
Reputation: 5425
This is how the code works:
Undergrad
called u
.u.method1()
Undergrad
doesn't define method2
, so it looks at its parent.Student
defines method2
, so it is called."Student 1 "
is printedStudent::method1
calls super.method1
, which looks at Person
"Person 1 "
is printed; the function returns to the stack point at 6Student::method1
calls method2
Undergrad
object. Since Undergrad
overrides method2
, it prints Undergrad 2
.method2
returns back to main
If you want to call method2
of a Student class, you'll need to find a Student
object that doesn't override method2
; that is, an actual normal student, not an undergrad.
Upvotes: 2