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: explanation (Page 3 of 6 )
This section will explain the code listed in the previous section. The class "Person" is defined with the following members:
name
setName
getDetails
The class "Lecturer" is defined with the following members:
qualification
getDetails
As the class "Lecturer" is inherited from "Person," it virtually contains the following members:
name
setName
getDetails
qualification
You must note that "getDetails" is available in both super and sub classes. From the class "Lecturer" point of view, it considers its own local method "getDetails," rather than the class "Person." Now, if we proceed to our "test" frame, we have the following initially:
Person p1 = new Person("Jag"); Lecturer l1 = new Lecturer("Chat", "M.Sc.");
The above will create two objects, "p1" (of class "Person") and "l1" (of class "Lecturer"). We call the method "getDetails" from both of those objects and display the information on the form using the following lines:
In the case of "p1.getDetails," it executes the method "getDetails," which belongs to the class "Person." In the later case of "l1.getDetails," it executes the method "getDetails," which belongs to the class "Lecturer." Make sure that it doesn't execute the method "getDetails" which is available in the "Person" class from the "Lecturer" object.
That means the method "getDetails" in the "Lecturer" class is given more preference than "getDetails" in the "Person" class for any "Lecturer" object. This is what is called overriding the methods.