Showing posts with label polymorphism. Show all posts
Showing posts with label polymorphism. Show all posts

Creating an Inheritance program in Java

Problem:

Create a class called Client that has the ID (int), First Name, Last Name (Strings), and amount(double) variables, and the AddMoney(), SubMoney() methods that are responsible respectively to add or subtract money to/from the amount.

Create a class called GoldenClient that inherits from the Client class, but have one more attribute which is char GoldenLevel that can be either ‘H’, ‘M’ or ‘L’. The GoldenLevel is set in method setGoldenLevel() method according to: ‘H’ if amount > 10000, ‘M’ if 5000 < amount < 10000, and ‘L’ if amount < 1000.

Create a class called PlatinumClient that inherits from the Client class, but have two more attributes: int numberOfTrips and double TravelOffersRate. It also has a method called addTrips(int n) that adds n trips to numberOfTrips. TravelOffersRate is calculated according to the formula: numberOfTrips*0.01. Make sure to update the value of TravelOffersRate when addTrips(int n) method adds trips to numberOfTrips.

Make sure to declare all Client’s variables as protected to allow inheritance.

Make sure to include the set, get and toString() methods in all classes. A toString() method will print the variable names and their corresponding values.

At the end, create the main class that contains the main method, create a new user and do some transactions.

Output:

Not needed.

Solution:

/**----------------------------Client.java--------------------*/
public class Client {
 
 protected int id;
 protected String firstName;
 protected String lastName;
 protected double amount;
 
 public Client(int id, String firstName, String lastName, 
                                                double amount) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.amount = amount;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public double getAmount() {
  return amount;
 }

 public void setAmount(double amount) {
  this.amount = amount;
 }
 
 public void addMoney(int toAdd) {
  amount += toAdd;
 }
 
 public void subMoney(int toSub) {
  amount -= toSub;
 }
 
 public String toString() {
  return "ID: "+id+"\nName: "+firstName+" "+
                          lastName+"\nAmount: "+amount+"\n";
 }
}
/**-----------------------ClientTest.java-----------------*/
public class ClientTest {
 
 public static void main(String args[]) {
  Client client = new Client(1, "Jon", "Snow", 10);
  GoldenClient goldenClient = new GoldenClient(2,
                                   "Jaime", "Lannister", 20000);
  PlatinumClient platClient = new PlatinumClient(5,
                                    "Arya", "Stark", 10000, 50);
  
  System.out.println(client);
  System.out.println(goldenClient);
  System.out.println(platClient);
  
  client.addMoney(1000000);
  client.subMoney(50000);
  
  goldenClient.subMoney(13000);
  goldenClient.setGoldenLevel();
  
  platClient.addTrips(10);
  
  System.out.println(client);
  System.out.println(goldenClient);
  System.out.println(platClient);
 }
}
/**-------------------GoldenClient.java-----------------*/
public class GoldenClient extends Client {

 private char goldenLevel;
 
 public GoldenClient(int id, String firstName, 
                          String lastName, double amount) {
  super(id, firstName, lastName, amount);
  setGoldenLevel();
 }
 
 public void setGoldenLevel() {
  if (amount > 10000)
   goldenLevel = 'H';
  else if (amount < 10000 && amount > 5000)
   goldenLevel = 'M';
  else if (amount < 1000)
   goldenLevel = 'L';
 }
 
 public char getGoldenLevel() {
  return goldenLevel;
 }
 
 public String toString() {
  return super.toString() + "Golden Level: "+
                                        goldenLevel+"\n";
 }
}
/**------------------PlatinumClient.java--------------*/
public class PlatinumClient extends Client {

 private int numberOfTrips;
 private double travelOffersRate;
 
 public PlatinumClient(int id, String firstName, 
     String lastName, double amount, int numberOfTrips) {
  super(id, firstName, lastName, amount);
  setNumberOfTrips(numberOfTrips);
 }

 public int getNumberOfTrips() {
  return numberOfTrips;
 }

 public void setNumberOfTrips(int numberOfTrips) {
  this.numberOfTrips = numberOfTrips;
  setTravelOffersRate(numberOfTrips*0.01);
 }

 public double getTravelOffersRate() {
  return travelOffersRate;
 }

 public void setTravelOffersRate(double travelOffersRate) {
  this.travelOffersRate = travelOffersRate;
 }

 public void addTrips(int n) {
  numberOfTrips += n;
  travelOffersRate = numberOfTrips*0.01;
 }
 
 public String toString() {
  return super.toString() + "Number of Trips: "+
         numberOfTrips+"\nTravel Offers Rate: "+travelOffersRate+"\n";
 }
}
Read More

Creating a Polymorphism and Histogram Application in Java

Problem:

User
- username : String
- password : String
- items[] : String
+ User(username : String, password : String, items[] : String)
+ setUsername(username : String) : void
+ getUsername() : String
+ setPassword(password : String) : void
+ getPassword() : String
+ setItems(items[] : String) : void
+ getItems() : String[]
# abstract getAccessibleItems() : String[]
+ toString() : String

Admin

+ Admin(username : String, password : String, items[] : String)
+ getAccessibleItems() : String[]
+ toString() : String

AccountingUser

+ AccountingUser(username : String, password : String, items[] : String)
+ getAccessibleItems() : String[]
+ toString() : String




In this assignment, you will be using inheritance and polymorphism to create an admin and an accounting user for some system.
The User class is an abstract class made up of a username, a password, and an array of accessible items. It has setter and getter methods and an abstract method called getAccessibleItems which should be implemented by subclasses of User.
The Admin class and the AccountingUser class are both subclasses of User. This means that you have to use inheritance to create both classes. Each of these classes' constructors must call the superclass constructor. Moreover, both of these classes have to implement the getAccessibleItems method which has to return an array of strings describing the items the user has access to.
Usually, a system admin has access to every item, while another user has access for a limited set of items. For example, the AccountingUser will have access to an accounting related item but not any other item.
Write a tester class which has an array of Users.
The array should contain one Admin and two AccountingUsers. After creating the users, you should loop over the array and use polymorphism to get the accessible items and print the user’s information.
Printing format is as follows:
(username)

Accessible items:
(getAccessibleItems())




Solution:
/**---------------AccountingUser.java--------------*/
public class AccountingUser extends User {

 public AccountingUser(String username, 
                  String password, String[] items) {
  super(username, password, items);
 }

 protected String[] getAccessibleItems() {
  String[] myItems = new String[2];
  
  myItems[0] = "Accounting View";
  myItems[1] = "Invoice View";
  
  return myItems;
 }
}

/**--------------Admin.java--------------------*/
public class Admin extends User {

 public Admin(String username, 
                   String password, String[] items) {
  super(username, password, items);
 }

 protected String[] getAccessibleItems() {
  return getItems();
 }
}
/**--------------User.java--------------------*/
public abstract class User {
 
 private String   username;
 private String   password;
 private String[] items;
 
 public User(String username, String password, 
                                      String[] items) {
  this.username = username;
  this.password = password;
  this.items = items;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String[] getItems() {
  return items;
 }

 public void setItems(String[] items) {
  this.items = items;
 }

 protected abstract String[] getAccessibleItems();
 
 public String toString() {
  return username+"\n\n";
 }
 
}
/**------------------------Tester.java---------------------*/
public class Tester {

 public static void main(String[] args) {
  
  String[] items = {"Accounting view", 
                "Invoice view", "HR view", "Admin view", 
                "Marketing view", "IT view"};
  
  User[] users = new User[3];
  
  users[0] = new Admin("admin", "admin", items);
  users[1] = new AccountingUser("AccUser", "acc123", items);
  users[2] = new AccountingUser("AccUser2", "123acc", items);
  
  for (int i = 0; i < users.length; i++) {
   
   if(users[i] instanceof Admin) {
    
   Admin currentUser = (Admin) users[i];
   String[] accessibleItems = currentUser.getAccessibleItems();
   System.out.println(currentUser+"Accessible Items:");
   for (int j = 0; j < accessibleItems.length; j++)
   System.out.print(accessibleItems[j] + " ");
    
   } else {
    
   AccountingUser currentUser = (AccountingUser) users[i];
   String[] accessibleItems = currentUser.getAccessibleItems();
   System.out.println(currentUser+"Accessible Items:");
    
   for (int j = 0; j < accessibleItems.length; j++)
    System.out.print(accessibleItems[j] + " ");
   }
  }
 }
}

Read More

Creating a Inheritance and Polymorphism Application in Java

Problem:

Vehicle
- manufacturer : String
- name : String
- engine : Engine
 - body : Body
- profit : double
+ Vehicle(manufacturer : String, name : String, engine : Engine, body : Body, profit : double) 
+ setManufacturer(manufacturer : String) : void
+ getManufacturer() : String
 + setName(name : String) : void
 + getName() : String
 + setEngine(engine : Engine) : void
+ getEngine() : Engine
+ setBody(body : Body) : void
+ getBody() : body
+ setProfit(profit : double) : void
 + getProfit() : double
 # abstract calculateTatalPrice() : double
+ toString() : String


Car
- doors : int
- gear : String
 - gearPrice : double
+ Car(manufacturer : String, name : String, engine : Engine, body : Body, profit : double, doors : int, gear : String, gearPrice : double)
+ setDoors(doors : int) : void
+ getDoors() : int
 + setGear(gear : String) : void
 + getGear() : String
+ setGearPrice(gearPrice : double) : void
 + getGearPrice() : double
+ calculateTotalPrice() : double
+ toString() : String     


Train
- compartments : int
- fuel : String
- cornpartmentPrice : double
+ Train(manufacturer : Stricw, name : String, engine : Engine, body : Body, profit : double, compartments : int, fuel : String, compartmentPrice : double)
+ setCompartments (compartments : int) : void
+ getCompartments () : int
+ setFuel(fuel : String) : void
 + getFuel() : String
 + setCompartmentPrice(compartmentPrice : double) : void
+ getCompartmentPrice () : double + calculateTotalPrice() : double
+ toString() : String


Engine
- id : String
- cost : double 
+ Engine(id : String, cost : double)
+ setld(id : String) : void
+ getld() : String
+ setCost(cost : double) : void
 + getCost() : double
 + toString() : String


Body
- width :
- height : double
- seats : int
 - cost : double
+ Body(width : double, height : double, seats: int, cost : double)
+ setWidth(width : double) : void
+ getWidth() : double
 + setHeight(height : double) : void
+ getHeight() : double
 + setSeats(seats : int) : void
+ getSeats() : int
+ setCost(cost : double) : void
+ getCost() : double
+ toString() : String

In this lab, you will be using inheritance to create a car and a train.
The Vehicle class is made up of an Engine and a Body and some other variables. It has setter and getter methods and a method called calculateTotalPrice which should be implemented by subclasses of Vehicle.
The Car class and the Train class are both subclasses of Vehicle. This means that you have to use inheritance to create both classes. Each of these classes' constructors must call the superclass constructor. Moreover, both of these classes have to implement the calculateTotalPrice method which has to sum up the total price of the vehicle plus the compartments' price if it is a train or the gear price if it is a car.
Write a tester class which has an array of Vehicles.
The array should contain two cars and two trains.
 Printing format is as follows:
(manufacturer) (name)
Engine:
(id) $(cost)

Body:
 (width)x(height)M
 (seats) seats
 (compartments) compartments (if train)
(doors) doors (if car)

Price:
 $(calculateTotalPrice())

Solution:
/**-----------------------Vehicle.java-------------------*/
public abstract class Vehicle {
 
 private String manufacturer;
 private String name;
 private Engine engine;
 private Body   body;
 private double profit;
 
 public Vehicle(String manufacturer, String name, 
                  Engine engine, Body body, double profit) {
  this.manufacturer = manufacturer;
  this.name         = name;
  this.engine       = engine;
  this.body         = body;
  this.profit       = profit;
 }

 public String getManufacturer() {
  return manufacturer;
 }

 public void setManufacturer(String manufacturer) {
  this.manufacturer = manufacturer;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Engine getEngine() {
  return engine;
 }

 public void setEngine(Engine engine) {
  this.engine = engine;
 }

 public Body getBody() {
  return body;
 }

 public void setBody(Body body) {
  this.body = body;
 }

 public double getProfit() {
  return profit;
 }

 public void setProfit(double profit) {
  this.profit = profit;
 }
 
 protected abstract double calculateTotalPrice();
 
 public String toString() {
  return manufacturer + " " + name + 
                     "\n\nEngine:\n" + engine.getId() + 
                   " $" + engine.getCost() + "\n\nBody:\n" + 
                    body.getWidth() + "x" + body.getHeight() +
                        "M\n" + body.getSeats() + " seats\n";
 }
}

/**-----------------------Car.java-------------------*/
public class Car extends Vehicle {

 private int    doors;
 private String gear;
 private double gearPrice;
 
 public Car(String manufacturer, String name, Engine engine,
                  Body body, double profit, int doors, String gear, 
                                                 double gearPrice) {
  super(manufacturer, name, engine, body, profit);
  this.doors     = doors;
  this.gear      = gear;
  this.gearPrice = gearPrice;
 }

 public int getDoors() {
  return doors;
 }

 public void setDoors(int doors) {
  this.doors = doors;
 }

 public String getGear() {
  return gear;
 }

 public void setGear(String gear) {
  this.gear = gear;
 }

 public double getGearPrice() {
  return gearPrice;
 }

 public void setGearPrice(double gearPrice) {
  this.gearPrice = gearPrice;
 }

 @Override
 protected double calculateTotalPrice() {
  return getEngine().getCost() + 
                   getBody().getCost() + getProfit() + gearPrice;
 }
 
 public String toString() {
  return super.toString() + doors 
         + " doors\n\nPrice:\n$" + calculateTotalPrice() + "\n\n";
 }
}
/**-----------------------Train.java-------------------*/
public class Train extends Vehicle {

 private int    compartments;
 private String fuel;
 private double compartmentPrice;
 
 public Train(String manufacturer, String name, Engine engine,
                 Body body, double profit, int compartments, 
                            String fuel, double compartmentPrice) {
  super(manufacturer, name, engine, body, profit);
  this.compartments = compartments;
  this.fuel = fuel;
  this.compartmentPrice = compartmentPrice;
 }

 public int getCompartments() {
  return compartments;
 }

 public void setCompartments(int compartments) {
  this.compartments = compartments;
 }

 public String getFuel() {
  return fuel;
 }

 public void setFuel(String fuel) {
  this.fuel = fuel;
 }

 public double getCompartmentPrice() {
  return compartmentPrice;
 }

 public void setCompartmentPrice(double compartmentPrice) {
  this.compartmentPrice = compartmentPrice;
 }

 @Override
 protected double calculateTotalPrice() {
  return getEngine().getCost() + getBody().getCost() 
                    + getProfit() + (compartments*compartmentPrice);
 }

 public String toString() {
  return super.toString() + compartments + 
        " compartments\n\nPrice:\n$" + calculateTotalPrice() + "\n\n";
 }
}

/**-----------------------Engine.java-------------------*/
public class Engine {
 
 private String id;
 private double cost;
 
 public Engine(String id, double cost) {
  this.id   = id;
  this.cost = cost;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public double getCost() {
  return cost;
 }

 public void setCost(double cost) {
  this.cost = cost;
 }
 
 public String toString() {
  return "";
 }
}
/**-----------------------Body.java-------------------*/
public class Body {
 
 private double width;
 private double height;
 private int    seats;
 private double cost;
 
 public Body(double width, double height,
                                   int seats, double cost) {
  this.width  = width;
  this.height = height;
  this.seats  = seats;
  this.cost   = cost;
 }

 public double getWidth() {
  return width;
 }

 public void setWidth(double width) {
  this.width = width;
 }

 public double getHeight() {
  return height;
 }

 public void setHeight(double height) {
  this.height = height;
 }

 public int getSeats() {
  return seats;
 }

 public void setSeats(int seats) {
  this.seats = seats;
 }

 public double getCost() {
  return cost;
 }

 public void setCost(double cost) {
  this.cost = cost;
 }
 
 public String toString() {
  return "Body:\n" + width + "x" + 
                             height + "M " + seats + " seats\n\n";
 }
}
/**-----------------------Tester.java-------------------*/
public class Tester {
 
 public static void main(String args[]) {
  
  Engine engine1 = new Engine("150511", 2000);
  Engine engine2 = new Engine("151211", 3000);
  Engine engine3 = new Engine("150911", 4000);
  Engine engine4 = new Engine("151515", 5000);
  
  Body body1 = new Body(2.3, 1.2, 2, 2000);
  Body body2 = new Body(2.6, 1.5, 4, 3000);
  Body body3 = new Body(20.3, 3.2, 50, 4000);
  Body body4 = new Body(30.3, 3.2, 70, 5000);
  
  Vehicle vehicles[] = new Vehicle[4];
  
  vehicles[0] = new Car("Company1", "Car1", 
                    engine1, body1, 10000, 2, "Manual", 500);
  vehicles[1] = new Car("Company2", "Car2", 
                    engine2, body2, 20000, 4, "Automatic", 400);
  vehicles[2] = new Train("Company1", "Train1", 
                    engine3, body3, 50000, 10, "Coal", 200);
  vehicles[3] = new Train("Company2", "Train2", 
                    engine4, body4, 100000, 20, "Electricity", 300);
  
  for (int i = 0; i < vehicles.length; i++) {
   if (vehicles[i] instanceof Train) {
    
    Train currentVehice = (Train) vehicles[i];
    System.out.println(currentVehice.toString());
    
   } else {
    
    Car currentVehice = (Car) vehicles[i];
    System.out.println(currentVehice.toString());
    
   }
  }
 }
}

Read More

Creating an Inhertiance Application in Java

Problem:

User
- username : String
- password : String
- items[] : String
+ User(username : String, password : String, items[] : String)
+ setUsername(username : String) : void
+ getUsername() : String
+ setPassword(password : String) : void
+ getPassword() : String
+ setItems(items[] : String) : void
+ getltems() : String[]
# abstract getAccessibleitems() : String[]
+ toString() : String


Admin

+ Admin(username : String, password : String, items[] : String)
+ getAccessibleitems() : String[]
+ toString() : String

AccountingUser

+ AccountingUser(username : String, password : String, items[] : String)
 + getAccessibleltems() : String[]
+ toString() : String


In this assignment, you will be using inheritance and polymorphism to create an admin and an accounting user for some system.

The User class is an abstract class made up of a username, a password, and an array of accessible items. It has setter and getter methods and an abstract method called getAccessibleltems which should be implemented by subclasses of User.

The Admin class and the AccountingUser class are both subclasses of User. This means that you have to use inheritance to create both classes. Each of these classes constructors must call the superclass constructor. Moreover, both of these classes have to implement the getAccessibleltems method which has to return an array of strings describing the items the user has access to.

Usually, a system admin has access to every item, while another user has access for a limited set of items. For example, the AccountingUser will have access to an accounting related item but not any other item.

Write a tester class which has an array of Users.

The array should contain one Admin and two AccountingUsers. After creating the users, you should loop over the array and use polymorphism to get the accessible items and print the user's information.

 Printing format is as follows:

 (username)
 
Accessible items: (getAccessibleltems())

Solution:

/**------------------User.java--------------*/
public abstract class User {
 
 private String   username;
 private String   password;
 private String[] items;
 
 public User(String username, String password, String[] items) {
  this.username = username;
  this.password = password;
  this.items = items;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String[] getItems() {
  return items;
 }

 public void setItems(String[] items) {
  this.items = items;
 }

 protected abstract String[] getAccessibleItems();
 
 public String toString() {
  return username+"\n\n";
 }
 
}

/**------------------Admin.java---------*/
public class Admin extends User {

 public Admin(String username, String password, String[] items) {
  super(username, password, items);
 }

 @Override
 protected String[] getAccessibleItems() {
  return getItems();
 }
}


/**-------------AccountingUser.java-------*/
public class AccountingUser extends User {

 public AccountingUser(String username, String password, String[] items) {
  super(username, password, items);
 }

 @Override
 protected String[] getAccessibleItems() {
  String[] myItems = new String[2];
  
  myItems[0] = "Accounting View";
  myItems[1] = "Invoice View";
  
  return myItems;
 }
}

/**------------------Tester.java-------------------*/
public class Tester {

 public static void main(String[] args) {
  
  String[] items = {"Accounting view", "Invoice view", "HR view", "Admin view", "Marketing view", "IT view"};
  
  User[] users = new User[3];
  
  users[0] = new Admin("admin", "admin", items);
  users[1] = new AccountingUser("AccUser", "acc123", items);
  users[2] = new AccountingUser("AccUser2", "123acc", items);
  
  for (int i = 0; i < users.length; i++) {
   
   if(users[i] instanceof Admin) {
    
    Admin currentUser = (Admin) users[i];
    
    String[] accessibleItems = currentUser.getAccessibleItems();
    
    System.out.println(currentUser+"Accessible Items:");
    
    for (int j = 0; j < accessibleItems.length; j++)
     System.out.print(accessibleItems[j] + " ");
    
    System.out.println("\n-------------------------------------------------------------------------------");
    
   } else {
    
    AccountingUser currentUser = (AccountingUser) users[i];
    
    String[] accessibleItems = currentUser.getAccessibleItems();
    
    System.out.println(currentUser+"Accessible Items:");
    
    for (int j = 0; j < accessibleItems.length; j++)
     System.out.print(accessibleItems[j] + " ");
    
    System.out.println("\n-------------------------------------------------------------------------------");
    
   }
  }
 }
}

Read More

Introduction to Polymorphism in Java

If I ask someone to put together a top-ten list of the most important working underlying principles for an object-oriented software development application, most likely polymorphism will make it at the top of list. Polymorphism is an extremely important principle of object-oriented software development.

To truly understand polymorphism, we need to explore one of the blueprints upon which polymorphism is actually built: binding. Think of binding as this piece that makes polymorphism bits.

But what do I actually mean by binding? Binding, if you like, is a commitment(decision) to execute a certain and particular piece of code, and that decision will be either made by the compiler or by the interpreter machine, during the execution of the code. When I say binding, I'm binding method invocation (A particular method definition). Now consider, the two types of binding in JAVA:

1) Early binding: If binding occurs by the compiler, then we talk about and refer to it as early binding (In other words, I had to do that binding before even executing that piece of code.)

Example:
Consider overloading a method, when you overload a method, you have the same method name but different set of parameters, consider the example below:
 int sum(int a , int b) {  
 return a + b;  
 }  
 int sum(int a , int b, int c) {  
 return a + b + c;  
 }  
Let's invoke this piece of code by calling: sum(1,2). Which one of the two versions you think will be executed? The first one. Why? Because you can count the number of parameters, identify the version that will be activated and be put in practice. So I'm here invoking sum(1,2) and I know which version will be called, but I need to need to link/connect that statement in appropriate method definition. Who would do the linking in your thinking? Can the compiler do it? Yes. The compiler actually will do the selection. So when it comes to calling overloaded methods, the compiler can make a commitment to execute a particular piece of code. The compiler is smart and can simply count the number of parameters to determine which version of the method should be executed or invoked actually. When dealing with overloaded methods, compiler selects the appropriate methods, this method selection strategy or procedure is called early binding. EARLY BINDING is called when handling OVERLOADED methods.


2) Late Binding: If binding occurs by the interpreter, then talk about and refer to it as call it late binding. Another name for late binding is dynamic binding. Late binding is used when a polymorphic reference is used. A polymorphic reference fits the definition of polymorphism itself. The meaning of the polymorphism itself actually means having many shapes or having many forms, incarnations. So a polymorphic reference will fit that definition and eventually it will embody that definition in the sense that a polymorphic reference is an object reference variable.

Example:
Consider overriding a method, when you override a method, you have a reference pointed twice, consider the example below:
 class Shape{  
   public void draw(){  
   System.out.println(“Draw a shape.”);  
   }  
 }  
 class Circle extends Shape{  
   public void draw(){  
   System.out.println(“Draw a circle.”);  
   }  
 }  
 class Test{  
   public static void main(String[] args){  
   Shape sh;   
   sh=new Circle(); //That's a polymorphic reference  
   sh.move(); //Print: "Draw a shape."  
   sh=new Shape();  
   sh.move(); //Print: "Draw a circle"  
   }  
 }  
It should be noted that in the first call to draw(), the reference type is Shape and the object being referenced is Circle. So, when a call to draw() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class Circle. So, the draw() method of Circle class will be called. In the second call to draw(), the object is of the class Shape. So, the draw() method of Shape will be called. Because we used a polymorphic reference to call a method, late binding takes place. Let me rephrase this: I will have to wait until the program runs before I will be able to determine which version of the method will be used. Interpreter will do the decision why? Because in this case the compiler cannot do it.it doesn't have the appropriate knowledge to make the appropriate decision, so it will be up to the interpreter to identify the method that should be executed. Late binding is less efficient then early binding because it involves making a decision during the execution of your code that will harm and degrade the performance of your programs in terms of running: amount of time to complete a task. There is a word called overhead associated with late binding: late binding is acceptable because of the flexibility offered by polymorphic references. Flexibility is the main key. This is our main target.

Keep In Mind:
Early binding or early polymorphism in Java is achieved by method overloading. Remember example 1.

Later binding or later polymorphism in Java is achieved by method overriding. Remember example 2.



Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact