Overriding methods

Overriding methods :

A method defined in a super class is inherited by its subclass and is used by the objects created by the sub class. Method inheritance enables us to define and use methods repeatedly in sub classes without having to define the methods again in sub class.

How ever there may be occasions when we want an object to respond to the same method but have different behaviour when that method is called. That means we should override the method defined in the super class.

In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

 

Program Illustrating method overriding

Class super

{

Int x;

Super(int x )

{

this.x = x ;

}

Void display()

{

System.out.println( “ Super X = “ + x);

}

}

Class sub extends super

{

Inty ;

Sub(int x , int y )

{

Super (x);

This.y=y;

}

Void display()

{

System.out.println(“super x = “ + x);

System.out.println(“ sub y = “ + y);

}

}

Class overridetest

{

Public static void main(string argd[])

{

Sub s1 = new sub(100,200);

S1.display();

}

}

Output :

Super x = 100

Sub y = 200

Leave Comment

Important Topics

Title
OOPS
Data Types
JAVA
JVM
Command Line Args
Machine Neutral
Scope of Variables
Operators :
Generic Type Casting
IF Else
Switch Statement
The while statement
The do statement
The for statement
Classes, objects and methods
Constructors
Methods Overloading
Static Members
Nesting of methods
Inheritance : Extending a Class
Overriding methods
Overriding methods
Final variable and methods
Abstract class in Java
Visibility control