java 我们可以使用多态将抽象类对象作为参数传递吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31381250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can we Pass Abstract Class Object as Argument Using Polymorphism?
提问by Zartash Zulfiqar
I have a class with name 'A'. A is an abstract class. And class 'B' extends class 'A'.
我有一个名为“A”的班级。A是抽象类。并且“B”类扩展了“A”类。
And I have another class 'C'. In class 'C' there's a function with name show().
我还有另一个“C”类。在“C”类中有一个名为 show() 的函数。
I want to pass an object of class 'A' which is abstract. Is it possible?
我想传递一个抽象的“A”类对象。是否可以?
Or
或者
Can we do this using Polymorphism.
我们可以使用多态来做到这一点。
If yes! then How?
如果是!那么如何?
回答by Fred Porciúncula
I want to pass an object of class 'A' which is abstract. Is it possible?
我想传递一个抽象的“A”类对象。是否可以?
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
).
即使A
是抽象的,您也可以接收类型的参数A
(在这种情况下,将是类型的对象B
)。
You cannot really pass an object of class A
, though, since A
is abstract and cannot be instantiated.
但是,您不能真正传递 class 的对象A
,因为它A
是抽象的并且无法实例化。
Can we do this using Polymorphism.
我们可以使用多态来做到这一点。
The above example actually already used polymorphism (subtyping).
上面的例子实际上已经使用了多态(subtyping)。
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
回答by Cleonjoys
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.
与上面的答案几乎相同,只是用代码详细说明。天真的说法,你不能在 new 运算符旁边有抽象类名,除非是数组,因为 A a[] = new A[10];
你仍然为数组中的每个元素分配了具体类的对象。
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);
}
}