In this article, I shall discuss the following topics on programming with OOPS (especially single/multilevel inheritance) in Java using NetBeans IDE: overriding in single inheritance, overriding in multilevel inheritance, and how to call super class methods during overriding.
Overriding Methods and Inheritance in Java - An example of overriding methods in single inheritance: code (Page 2 of 6 )
I already introduced different types of inheritance in my previous articles. In this section, I shall introduce you to the concept of overriding methods in inheritance. The concept of overloading is totally different from that of overriding methods. Let us start with an example.
Open your NetBeans project (as given in my previous article), and modify your code in "Person.java" so that it looks something like the following:
public class Person {
String name; /** Creates a new instance of Person */ public Person() { }
public Person(String n) { name = n; } public void setName(String s) { name = s; }
Modify your code in "Lecturer.java" so that it looks something like the following:
public class Lecturer extends Person { String qualification; /** Creates a new instance of Lecturer */ public Lecturer() { }
public Lecturer(String n, String q) { name = n; qualification = q; }
public String getDetails() { return "Name = " + name + ", Qualification = " + qualification; } }
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: Person p1 = new Person("Jag"); Lecturer l1 = new Lecturer("Chat", "M.Sc."); this.lblMsg.setText(p1.getDetails()); this.lblMsg2.setText(l1.getDetails()); }