Week 8
Week 8
In Java, we can override methods only, not the variables(data members), so runtime polymorphism
cannot be achieved by data members.
Run-time Polymorphism: Method Overriding (Concept)
9
class Vehicle
{
void run()
{}
}
class Bike2 extends Vehicle
{
void run()
{}
}
Method Overriding (Example)
13
class Human
{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
public static void main( String args[])
}
class Boy extends Human
{
{ Boy obj = new Boy();
//Overriding method //This will call the child class version of eat()
public void eat(){ obj.eat();
System.out.println("Boy is eating"); }
}
Method Overriding (Example)
15
class Bank
{
int getRateOfInterest() {return 0;}
}
//Creating child classes.
class HBL extends Bank
{
int getRateOfInterest() {return 8;}
}
class UBL extends Bank
{
int getRateOfInterest() {return 7;}
}
class ABL extends Bank
{
int getRateOfInterest() {return 9;}
}
Method Overriding (Example)
16
class Test2
{
public static void main(String args[])
{
HBL h=new HBL();
UBL u=new UBL();
ABL a=new ABL();
System.out.println(“HBL Rate of Interest: "+h.getRateOfInterest());
System.out.println(“UBL Rate of Interest: "+u.getRateOfInterest());
System.out.println(“ABL Rate of Interest: "+a.getRateOfInterest());
}
}
It is because the static method is bound with class whereas the instance method
is bound with an object. Also, static methods are resolved at compile-time based
on the class in which they are defined, rather than being dynamically resolved,
the concept of method overriding does not apply to static methods in Java