-2

what is the benefit of dynamic binding over static one.. If we want to access the methods of sub class then we can make an object of the same with reference variable of sub class type…. what is the benefit if we want to call a method of sub class and using reference variable of super class type?

class Human{
   public void walk()
   {
       System.out.println("Human walks");
   }
}
class Boy extends Human{
   public void walk(){
       System.out.println("Boy walks");
   }
   public static void main( String args[]) {
       //Reference is of parent class
       Human myobj = new Boy();
       myobj.walk();
   }
}
O/p :Boy walks

In the above example why do we need to use "Human myobj = new Boy();" instead we can use "Boy myobj = new Boy();" My point is what is the use of assigning super class reference to sub class object. I am really confused about this. Please help me..

priyanka
  • 11
  • 2

1 Answers1

0

You can use either,

Human myobj = new Boy();

or

Boy myobj = new Boy();

depending on what you want to achieve. If Boy had an additional method

playWithOther(Boy boy)

and the remaining code needs to call this method, than you have to use the latter version. If the remaining code doesn't need to call any Boy specific methods, then it's usually considered good practice to use the more generic super class. That way you indicate that the remaining code will work with any Human object, so a simple replacement of Boy with Girl

Human myobj = new Girl();

will work. You can find many examples for this, e.g.

java.util.List
java.util.ArrayList
java.util.LinkedList

In your code, you should generally define variables as java.util.List and then instantiate either one of the list implementations (or any other class, that implements the List interface). This approach allows you to change the implementation of the List interface at a single place were you create the List object. The rest of the code will not require any syntax changes if you use a different List implementation.

Guenther
  • 2,035
  • 2
  • 15
  • 20