dollaza
dollaza

Reputation: 213

how to call a method without calling its subclass

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

Answers (2)

Veltro
Veltro

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

hyperneutrino
hyperneutrino

Reputation: 5425

This is how the code works:

  1. You create an Undergrad called u.
  2. You call u.method1()
  3. Undergrad doesn't define method2, so it looks at its parent.
  4. Student defines method2, so it is called.
  5. "Student 1 " is printed
  6. Student::method1 calls super.method1, which looks at Person
  7. "Person 1 " is printed; the function returns to the stack point at 6
  8. Student::method1 calls method2
  9. Keep in mind that this is technically referring to the Undergrad object. Since Undergrad overrides method2, it prints Undergrad 2.
  10. 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

Related Questions