Reputation: 765
I have a class Person and its subclass Student:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student extends Person {
private int grade;
public Student(String name, int grade) {
super(name);
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void printDescription() {
System.out.println("Name: " + getName());
System.out.println("Grade: " + Integer.toString(grade));
}
}
So Person have getter and setter for name property and Student have only getter and setter for its new grade property, as long as a printDescription() method. The problem is how should I call the name property in Student's printDescription() method correctly?
I implemented it like in code above considering that Student inherits getter and setter from parent class. But at my university Java teacher asks to use it like this:
public void printDescription() {
System.out.println("Name: " + super.getName());
System.out.println("Grade: " + Integer.toString(grade));
}
So he offers to directly call parent's getter. I think it is not the best way because in case we override name's getter in Student class, getter from Person will still be called instead.
So what approach is best in this situation to use name property?
UPD: it is important to mention that for this task there is no requirement to call specifically superclass' getter implementation, this is why I was confused by teacher's recommendation to use super.
Upvotes: 0
Views: 13676
Reputation: 1075
You're correct that if you override the method in the subclass and you're using the super keyword then you'll invoke the method on the parent class.
In this case unless you wanted to guarantee that the method in the parent class was used then it's fine to just invoke the method without the super keyword and that way if you override the method then you get the behaviour you want in the subclass.
Upvotes: 2
Reputation: 1178
if you extends a class , it will has all properties in its superclass. instead of calling super.getName()
you can just call this.getName()
.
Upvotes: 0