Method Overriding (OOP - JAVA)
Method Overriding
Changing the body of a method which comes from a super class to a sub class called method overriding.
The method which is related to the object, run always.
Consider the following example.
class Monkey{
void climb(){
System.out.println("Using body");
}
}
class Man extends Monkey{
void climb(){
System.out.println("Using ladder");
}
}
super class - Monkey
sub class - Man
if we create a object using Man class,
Man m = new Man();
m.climb();
The output => Using ladder
super keyword
We use super keyword to call the constructor of super class from a sub class.
Always we call the super class from this keyword. We can access the methods and variables inside the super class from a sub class by using super keyword.
Check the following example.
class Monkey{
Monkey(){
}
void climb(){
System.out.println("Using body");
}
void eat(){
System.out.println("Eating");
}
}
class Man extends Monkey{
Man(){
}
void climb(){
System.out.println("Using ladder");
}
super();
super.climb();
super.eat();
}
You can see how to use method overriding by checking following code examples as well.
ex 1:
public class Human {
void run(){
System.out.println("Human can eat");
}
}
class Gawesh extends Human{
void run(){
System.out.println("Gawesh can eat");
}
public static void main(String[] args) {
Gawesh g = new Gawesh();
g.run();
}
}
ex 2:
class Samsung extends Mobile{
public void displayName(){
System.out.println("Samsung Galaxy Note 22 ULTRA");
super.displayName();
}
}
class Apple extends Samsung{
public void displayName(){
System.out.println("Iphone 14 Pro Max");
super.displayName();
}
}
class Run {
public static void main(String[] args) {
Samsung s = new Samsung();
Apple a = new Apple();
s.displayName();
a.displayName();
}
}
ex 3:
public class CentralBank {
int getInterestRate(){
return 0;
}
}
class BOC extends CentralBank{
int getInterestRate(){
return 8;
}
}
class PeoplesBank extends CentralBank{
int getInterestRate(){
return 10;
}
}
class CommercialBank extends CentralBank{
int getInterestRate(){
return 12;
}
}
class TestOverriding{
public static void main(String[] args) {
BOC b = new BOC();
PeoplesBank p = new PeoplesBank();
CommercialBank c = new CommercialBank();
System.out.println("Interest Ratw: " + b.getInterestRate() + "%");
System.out.println("Interest Ratw: " + p.getInterestRate() + "%");
System.out.println("Interest Ratw: " + c.getInterestRate() + "%");
}
}
I think, you can try above coding examples on your own IDE and understand how we can apply method overriding practically.


Comments
Post a Comment