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?
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With