Polymorphism is working perfectly fine for the following code:
class ClassA { String whoAmI() { return "ClassA"; } } class ClassB extends ClassA{ String whoAmI() { return "ClassB"; } } class Main { public static void main(String[] args) { ClassA obj1 = new ClassA(); ClassA obj2 = new ClassB(); System.out.println(obj1.whoAmI()); System.out.println(obj2.whoAmI()); } } Output of the code above is:
ClassA ClassB ButIn the code above output is as expected that I can see the methods of class "ClassB" when I am running following code then Compilercreating a reference variable of class "ClassA" and instantiating with "new ClassB();", but why it is giving exceptionnot same in case when I creating the reference variable of interface "List" and instantiating it by using its implementing class "ArrayList" (I know that we can't create objects of interfaces directly)?
import java.util.ArrayList; import java.util.List; public class ClassAMain { Stringpublic whoAmIstatic void main(String[] args) { return "ClassA"; List } }objList class= Mainnew {ArrayList(); public static void main(String[] argsobjList.add("One") {; objList.add("Two"); Object obj1 = new ClassAobjList.add("Three"); obj1 System.whoAmIout.println(objList.get(1)); // Only able to }call methods of } Output of the code above:
Exceptioninterface in"List", threadbut "main"not java.lang.RuntimeException:methods Uncompilableof sourceits codeimplementing -class Erroneous"ArrayList. symWHY?" type: java.lang.Object.whoAmI } } My question is when "ClassA" is implicitly extendingIf class "Object""ArrayList" is implementing interface "List" then why methods of class "ClassA" isI am not availableable to object "obj1" by following the principles of Polymorphism? Onlycall methods of class "Object" are available for object "obj1"."ArrayList"?
I know that there is some misunderstanding in my mind about the concept of Polymorphism. Please help me to clear that misunderstanding!