Overriding Methods and Inheritance in Java - How to call super class methods during overriding
(Page 6 of 6 )
Now, let me conclude by raising a small issue. Let us consider that I would like to execute a method in the super class which already exists in the sub class with the same name. This scenario is a bit different. Let us consider the following example:
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 = getSum() + d;
return t;
}
}
If you execute the program with the above modified class, it would result in a "Stack Overflow" error, as it tries to execute "getSum" from itself an infinite number of times. In this case, you need to modify it to look something 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 = super.getSum() + d;
return t;
}
}
I hope you can understand the usage of "super" in the above example.
The entire code for this article is freely available in the form of a zip file. That downloadable solution was developed using NetBeans 4.1 IDE together with Microsoft Windows 2003 Standard Edition. I didn't really test it in any other version or platform. Please follow the respective platform documentation to get it working. This series is dedicated for the beginners who wanted to work with NetBeans IDE.
Any doubts, bugs, errors, suggestions, feedback etc. are highly appreciated at jag_chat@yahoo.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |