Home > OS >  how can we call add method on List if the interface List not implement the method add()?
how can we call add method on List if the interface List not implement the method add()?

Time:12-31

I'm new in programming and really got stuck here. if we have an implemented method in a superclass and trying to call it from an instance of its subclass having the superclass type in its reference then the inherited method will not work. BUT why method add() works in this case if we have type List here instead of ArrayList?

List<String> testMethodsFromArrayList = new ArrayList<String>();
    
    TestClass () {
        testMethodsFromArrayList.add("1");
    }

playing with compiler I noticed that interfaces allow to do that but classes not.

CodePudding user response:

This is how run time polymorphism works in Java.

The parent class reference can refer to object of parent class or any of it's child class. Depending on which class's object parent class reference is referencing to, that class's method would be invoked.

List<String> testMethodsFromArrayList = new ArrayList<String>();

As in this case parent class(interface) reference 'testMethodsFromArrayList' is pointing to object of ArrayList, so ArrayList's add method is getting called.If you change it to following :

List<String> testMethodsFromArrayList = new LinkedList<>();

Then add() method of LinkedList would get called.

And regarding your comment "for example if I use superclass type reference then a method can't be invoked which is implemented in its subclass", you are partially right here, as using parent class reference you can call only overriden methods of child class which are defined/declared in interface/superclass as well. You can not invoke a method defined only in child class and which is not declared/defined in superclass/interface, using a parent class/interface reference as parent does not even know about that method.

CodePudding user response:

Add method is an inbuilt method in the ArrayList class,

you can find more details here as a reference: https://www.javatpoint.com/java-arraylist

  • Related