Method overriding is a mechanism in which a subclass inherits the methods of superclass and sometimes the subclass modifies the implementation of a method defined in superclass.
Method Overriding
Method overriding is a mechanism in which a
subclass inherits the methods of superclass and sometimes the subclass modifies
the implementation of a method defined in superclass. The method of superclass
which gets modified in subclass has the same name and type signature. The
overridden method must be called from the subclass. Consider following Java
Program, in which the method(named as fun) in which a is assigned with some
value is modified in the derived class. When an overridden method is called
from within a subclass, it will always refer to the version of that method
re-defined by the subclass. The version of the method defined by the superclass
will be hidden.
Java
Program[OverrideDemo.java]
class A
{
int a=0;
void
fun(int i)
{
this.a=i;
}
}
class B
extends A
{
int b;
void
fun(int i)
{
int c;
b=20;
super.fun(i+5);
System.out.println("value
of a:"+a);
System.out.println("value
of b:"+b);
c=a*b;
System.out.println("The
value of c= "+c);
}
}
class
OverrideDemo
{
public
static void main(String args[])
{
B obj_B
=new B();
obj_B.fun(10);//function
re-defined in derived class
}
}
Output
F:\test>javac
OverrideDemo.java
F:\test>java
OverrideDemo
value of
a:15
value of
b:20
The
value of c= 300
Program
Explanation
In above
program, there are two class - class A and class B. The class A acts as a
superclass and the class B acts as a subclass. In class A, a method fun is
defined in which the variable a is assigned with some value. In the derived
class B, we use the same function name fun in which, we make use of super
keyword to access the variable a and then it is multiplied by b and the result
of multiplication will be printed.
Rules to be followed for method overriding
1. The
private data fields in superclass are not accessible to the outside class. Hence
the method of superclass using the private data field cannot be overridden by
the subclass.
2. An instance method can be overridden only
if it is accessible. Hence private method can not be overridden.
3. The
static method can be inherited but can not be overridden.
4.
Method overriding occurs only when the name of the two methods and their type
signatures is same.
Difference between Method Overloading and
Method Overriding
Review
Questions
1.
Differentiate between method overloading and method overriding. Explain both
with an example.
2. What
is meant by overriding method? Give example.
Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : with Example Java Programs - Method Overriding
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation