2

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?

Zartash Zulfiqar
  • 93
  • 1
  • 3
  • 13

2 Answers2

4

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

Yes, it is. The following is valid:

abstract class A {}

class B extends A {}

class C {
    public void show(A a) {}
}

Even though A is abstract, you can receive parameters of type A (which, in this case, would be objects of type B).

You cannot really pass an object of class A, though, since A is abstract and cannot be instantiated.

Can we do this using Polymorphism.

The above example actually already used polymorphism (subtyping).

https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping

Fred Porciúncula
  • 8,533
  • 3
  • 40
  • 57
3

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);
       }
}
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
Cleonjoys
  • 504
  • 4
  • 10