Dynamic binding example

Dynamic binding example
Dynamic binding: It is a case in java where compiler is unable to decide which method to call at compilation time. Only JVM decides which method is called at runtime. Below program is an example of "dynamic binding" or "late binding".
 package com.ram;

interface Area{
 public int area(int length);
}

class Square implements Area{

 @Override
 public int area(int length) {
  int squareArea = length * length;
  return squareArea;
 }
}

class Circle implements Area{

 @Override
 public int area(int length) {
  double circleArea = (22.0/7.0) * length * length;
  return (int)circleArea;
 }
}

public class CalculateArea {
 public static void main(String[] args){
  Area areaObj1 = new Square();
  Area areaObj2 = new Circle();
  
  System.out.println("Square area = "+areaObj1.area(10));
  System.out.println("Circle area = "+areaObj2.area(10));
 }
}
 
 
Execute CalculateArea class and you get the below output:
Square area = 100
Circle area = 314

No comments:

Post a Comment