Method Overridding in Java Using Netbeans IDE

Introduction

This article describes how method overridding works in Java. The Netbeans IDE is used for the develoment of examples.

What is Method Overridding

Method overridding is defined as having two methods with the same something in multiple classes and one method is overridden by another method. It is a part of polymorphism, polymorphism is a feature of Java. The word polymorphism means a formation of two; poly means many and morphism means forms, using polymorphism the object can take many forms. There are two types of Polymorphism as in the following:

  • Static

          Static polymorphism is defined as having two methods with the same name within the same class, for example Method Overloading.

  • Dynamic

          Dynamic polymorphism is defined as having two methods with the same name in different class, for example Method Overridding.

Feature Used for doing Overridding

For doing overridding in Java we use inheritance. Inheritance is a feature of Java in which a method of one class can be used in another class.

Rules for doing Method Overridding

  • While overridding a method the argumentlist must be the same as for the overridden method.
  • The method in the overridden class must not be protected or private.
  • For overridding, a method must not declared final.
  • For overridding, a method must not declared static.
  • For overridding, a method must be inherited.
  • In method overidding constructors cannot be overidden.

Example

In this example; we define method overidding using the Netbeans IDE. There are certain steps in the Netbeans IDE that we need to follow as explained below.

Step 1

Open the Netbeans IDE.

fig 1.jpg

Step 2

Click on "File" from the Menu bar as in the following:

fig 2.jpg

Step 3

Click on "New Project" as in the following:

fig 3.jpg

Step 4

Select "Java" and "Java application" as in the following:

fig 4.jpg

Step 5

Click on "Next" as in the following:

fig 5.jpg

Step 6

Instead of project name specify "OverRiddingDemo" and instead of main class also specify "OverRiddingDemo" and click on "Finish".

fig 6.jpg

Step 7

In this class write the following code (the class name is "OverRiddingDemo"):

class OverRiddingDemo

{

      void disp()

{

    System.out.println("i provide the black color");

}

}

class Child extends OverRiddingDemo

{

@Override

void disp()

{

   System.out.println("i provide blue color");

    

}

public static void main(String... args)

{

Child obj=new Child();

obj.disp();

}

}

fig 7.jpg

Step 8

Now go to OverRiddingDemo.Java and right-click on that, click on "Run" from the menu bar as in the following:

fig 8.jpg

Output

 The output is "we Provide the blue color", the method "void disp()" in the OverRiddingDemo Class is overridden by the method "void disp()" in the child class.

fig 9.jpg