Dynamic polymorphism

Dynamic polymorphism

The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a method is called, the method call is bound to method body at the time of running the program, dynamically.In this case java compiler does not know which method is called at the time of compilation. Only JVM knows at runtime which method is to be executed.

Program
class sample
{
void add(int a,int b)
{
System.out.println(“sum of two number “+(a+b));
}
void add(int a,int b,int c)
{
System.out.println(“sum of three number “+(a+b+c));
}
}
class test
{
public static void main(String args [])
{
sample s=new sample();
s.add(10,20); //this call is bound with first method
s.add(10,20,30);//this call is bound with second method
}
}

Output:
sum of two number 30
sum of three number 60

Program
class account
{
void deposit(double amt)
{
System.out.println(“to deposit the amount”);
}
void withdraw(double amt)
{
System.out.println(“to withdraw the amount”);
}
void viewBal()
{
System.out.println(“to view the account balance”);
}
}
class savingaccount extends account
{
double accBal;
savingaccount(double initialamt)
{
System.out.println(“opening the saving account with Rs” + initialamt);
}
void deposit(double amt)
{
System.out.println(“depositing amount Rs “+ amt);
accBal = accBal+amt;
}
void withdraw(double amt)
{
System.out.println(“withdrawing an amount of Rs”+ amt);
accBal = accBal-amt;
}
void viewBal()
{
System.out.println(“Current balance is “+ accBal);
}
}
class loanaccount extends account
{
double accBal;
loanaccount(double loanamt)
{
System.out.println(“openning the saving account with Rs” + loanamt);
}
void deposit(double amt)
{
System.out.println(“depositing amount Rs “+ amt);
accBal = accBal-amt;
}
void withdraw(double amt)
{
System.out.println(“withdrawing an amount of Rs”+ amt);
accBal = accBal+amt;
}
void viewBal()
{
System.out.println(“Outstanding balance is “+ accBal);
}
}
class test
{
public static void main(String[] args)
{
account a = new loanaccount(1000.00);
a.viewBal();
a.withdraw(2000.00);
a.viewBal();
a.deposit(4000.00);
a.viewBal();
}
}

Output:
openning the saving account with Rs1000.0
Outstanding balance is 0.0
withdrawing an amount of Rs2000.0
Outstanding balance is 2000.0
depositing amount Rs 4000.0
Outstanding balance is -2000.0

Leave a Reply

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