Function overriding

In this section, let's discuss one more important feature in Java—is function overriding. Let's continue with the same example that we looked at when learning about inheritance.

In that example, we had a parent class called parentClassdemo and a child class called childClassDemo, and the child class inherited the parent class, as follows:

package coreJava;
public class childClassDemo extends parentClassdemo {

public void engine()
{
System.out.println("new engine");
}

public static void main(String[] args) {
childClassDemo cd=new childClassDemo();
cd.color();
}

Here, we have the engine method defined in the child class, which prints a new engine, and we have another method, color, which is defined in the parent class, and we call it using an object. If we print this, we will get the output of the color method, as it is defined in the parent class. Now, we create a new method in the child class and name it color as well, defining it as follows:

    public void color()
{
System.out.println("update color");
}

We have two instances of the color method—one defined in the parent class and a new one defined in the child class. Here is where the concept of function overriding comes into action. If you run the child class, you will get the output of update color. This is because the new color method defined in the child class overrides the color method from the parent class.

This sums up the whole concept of function overriding, where both the methods have the same name, signature, and parameters. In function overloading, we have methods that have the same name, but different arguments. This, one of the major differences between function overloading and function overriding.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.143.181