Method Overriding in Java
In this class, We discuss Method Overriding in Java.
The reader should have prior knowledge of methods in Java. Click Here.
We take an example and understand the concept of method overriding.
Example:
class A
{
int P;
void m1()
{
System.out.println(“class A”);
}
}
Class B extends A
{
int q;
void m1()
{
System.out.println(“class B”);
}
}
class test
{
public static void main(String args[])
{
B ob = new B();
ob.m1();
}
}
In the program, we have two classes.
Class B is extending class A.
class A has method “m1”.
Class B has the method “m1” same signature as in class A.
Methods having the same signature in super and subclass are called method overriding.
Method overriding is allowed in Java.
Two points to understand:
1) Suppose we need to use the method “m1” present in class A; how to access it?
Our next class will discuss how we access the method present in class A.
2) We created an object for class B
When we access the method ob.m1(), the method in class B is accessed.
The execution will check the methods in class B first. If not available, then check in super class A.