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 multilevel chain type inheritance: code and explanation (Page 5 of 6 )
In the previous section, I gave an example of overriding methods in a multilevel inheritance (tree type). Now I shall extend the same to the chain type of multilevel inheritance.
From within the "Project" view, add three more classes with names "First," "Second" and "Third." Modify the code in "First.java" in such a way that it looks like the following:
public class First { int a,b; /** Creates a new instance of First */ public First() { }
public First(int p, int q) { a = p; b = q; }
public int getSum() { int t; t = a + b; return t; } }
Modify the code in "Second.java" in such a way that it looks like the following:
public class Second extends First { int c;
public Second() { }
/** Creates a new instance of Second */ public Second(int m, int n, int p) { a = m; b = n; c = p; }
public int getSum() { int t; t = a + b + c; return t; } }
Modify the code in "Third.java" in such a way that it looks like the following:
public class Third extends Second { int d; /** Creates a new instance of Third */ public Third() { }
public Third(int l, int m, int n, int p) { a = l; b = m; c = n; d = p; }
public int getSum() { int t; t = a + b + c + d; return t; } }
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: Second obj1 = new Second(10, 20, 30); Third obj2 = new Third (10, 20, 30, 40); this.lblMsg.setText(String.valueOf(obj1.getSum())); this.lblMsg2.setText(String.valueOf(obj2.getSum())); }
According to the above code, it now executes the method "getSum" of "obj1" and also the method "getSum" of "obj2." But none of it really executes "getSum" of the class "First."