overriding in java

If child class has the same method as declared in the parent class is known as method overriding.

In other words , if the subclass provides special implimentation of a method that is already provided by parent class is known as method overriding.

Method overriding is used to provide special implementation of method in child class that is already provided by parent class.

It is used for runtime polimerphism.

In overriding, method must have same name and parameter as in parent class.

It must be IS-A relationship(inheritance).

EXAMPLE:

class vehicle
{
void run()
{
System.out.println(“vehicle is runnning”);
}
}
class overriding extends vehicle
{
void run()
{
System.out.println(“bike is running safely”);
}
public static void main(String args[])
{
overriding ob=new overriding();
ob.run();
}
}

OUTPUT-bike is running safely.

EXAMPLE:

Consider a scenario, bank is a class that provides functionality to get rate of interest.But rate of interest varies according to banks. For example ,sbi,icici and axis bank could provide 8%,7% and 9% rate of inerest.

answer:

class bank
{
int interest()
{
return 0;
}
}
class sbi extends bank
{
int interest()
{
return 8;
}
}
class axis extends bank
{
int interest()
{
return 9;
}
}
class icici extends bank
{
int interest()
{
return 7;
}
}
class overriding1
{
public static void main(String arg[])
{
sbi s= new sbi();
icici i=new icici();
axis a=new axis();
System.out.println(“sbi rate of interest=”+s.interest());
System.out.println(“icici rate of interest=”+i.interest());
System.out.println(“axis rate of interest=”+a.interest());

}

}

OUTPUT:

sbi rate of interest:8

icici rate of interest:7

axis rate of interest:9

     

Read More

Leave a Reply

Your email address will not be published. Required fields are marked *