Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
<pre>class Alpha
{
    public String doStuff(String msg)
    {return msg;}
}
class Beta extends Alpha
{
    public String doStuff(String msg)
    { return msg.replace('a','e');}
}
public class Main extends Beta
{ public String doStuff(String msg)
{
    return msg.substring(2);
}
  public static void main (String[]args)
  {
    List <Alpha> strs=new ArrayList<>();
    strs.add(new Alpha());
    strs.add(new Beta());
    strs.add(new Main());
    for(Alpha t:strs)
    {    
        System.out.println(t.doStuff("Java"));
    }
}
}

output
Java
Jeve
va

What I have tried:

my understanding is that :

In the for loop,
first iteration,
the anonymous object of Alpha and object 't' of Alpha will be pointing to the same location so we get the output as Java

but in the second iteration,
the properties of the anonymous object of Beta will be assigned to 't' which I expected will throw an error but the program produces the output.

Could anyone explain what's happening in the second and third iterations ?
Posted
Updated 20-Jul-18 0:40am

1 solution

It is a Polymorphism (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)[^] feature.

The above link describes it, provides an example similar to yours, and finally nails it down:
Quote:
The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.

In your example the objects in the list are of type Alpha, Beta, and Main. Even while t is declared as Alpha, the appropriate doStuff() method of the "real" object is called.
 
Share this answer
 
Comments
@k5hu 20-Jul-18 9:13am    
Thank you so much :) I was confused with upcasting. Now am clear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900