Overriding Methods and Inheritance in Java - An example of overriding methods in multilevel tree type inheritance: code and explanation
(Page 4 of 6 )
In the previous sections, I simply gave an example of overriding methods in a single inheritance. Now, I shall discuss overriding methods in a multilevel inheritance (tree type).
Add a new class, "Student," to the existing solution. Modify the code in "Student.java" in such a way that it looks like the following:
public class Student extends Person {
String course;
/** Creates a new instance of Student */
public Student() {
}
public Student(String n, String c) {
name = n;
course = c;
}
public String getDetails() {
return "Name = " + name + ", Qualification = " + course;
}
}
Now, go back to the frame "test.java." Double click on it to open and then double click on the button to open source view. Within the source view, modify your "buttonActionPerformed" in such a way that it looks like the following:
private void btnShowActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Student s1 = new Student("Jag","B.Sc.");
Lecturer l1 = new Lecturer("Chat", "M.Sc.");
this.lblMsg.setText(s1.getDetails());
this.lblMsg2.setText(l1.getDetails());
}
According to the above code, it now executes the method "getDetails" of "s1" and another method, "getDetails" of "l1". But none of it really executes "getDetails" of the class "Person."
Next: An example of overriding methods in multilevel chain type inheritance: code and explanation >>
More Java Articles
More By Jagadish Chaterjee