Search code examples
javapolymorphismabstract-class

Can we Pass Abstract Class Object as Argument Using Polymorphism?


I have a class with name 'A'. A is an abstract class. And class 'B' extends class 'A'.

And I have another class 'C'. In class 'C' there's a function with name show().

I want to pass an object of class 'A' which is abstract. Is it possible?

Or

Can we do this using Polymorphism.

If yes! then How?


Solution

  • Pretty much the same as above answer, just elaborated with code. Naive way of telling, you cannot have abstract class name next to new operator except in case with array, as in A a[] = new A[10]; where you have still allocate Objects of concrete class for each element in Array.

    abstract class A{
            abstract void tell();
    }
    
    class B extends A{
            void tell(){
                    System.out.println("I am B Telling");
            }
    }
    
    public class Test{
    
            public static void whoTold(A a)
            {
                    a.tell();
            }
    
            public static void main(String[] args){
                    B b = new B();
                    whoTold(b);
           }
    }