Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inheritance and overriding a method

Tags:

java

I'm just learning about inheritence and am stuck on a simple problem. I want to override the print() statement in the one class with a new one in it's subclass two. I'm not sure how I would approach it as it is a void statement with no parameters.

  public class One {

    private String name;
    private int age;

    public human(String n, int a)
      name = n;
      age = a;
    }
    public void print() {

     System.out.println("Name: " + name);
     System.out.println("Age: " + age);

    }

Second class:

    public class Two extends One {

    private double gpa;

    public two(String n, int a, double g) {
      super(n,a);
      gpa = g;

    public double getGPA (){
          return gpa;
       }

    public void print() {
    // override code here to include code from class one + displaying GPA..

     }
}

So for example, example.print() would print

Name: Jack
Age: 34

The desired output I want is

Name: Jack
Age: 34
GPA: 3.20

I am thinking I have to use the super method but cannot find a way to incorporate it correctly. Any tips would be appreciated!

like image 929
aiuna Avatar asked Dec 01 '22 19:12

aiuna


1 Answers

The keyword super gives you access to (visible) members of the superclass. So, you could call the print() method of the superclass, and then just do the specific work of the subclass:

public void print() {
    super.print();
    System.out.println ("GPA: " + gpa);
}

See this brief section of the Java Tutorials for more on the usage of super: Using the Keyword super. It does address with a simple example the very same problem you were asking about.

Please note that if you wrote

public void print() {
    print();
    System.out.println ("GPA: " + gpa);
}

Without specifying that you want to call super.print(), the print() method of two would be calling itself indefinitely until you got an OutOfMemoryError.

It is also worth noting what Vash mentioned about the @Override annotation in his answer.

like image 131
Xavi López Avatar answered Dec 04 '22 09:12

Xavi López