[英]Cannot resolve method when passing a concrete class
Why is this an invalid syntax?为什么这是无效的语法? I thought polymorphism will occur in this example.
我认为在这个例子中会出现多态。 The shape could be known only in runtime and it should be dispatched to the correct method.
形状只能在运行时知道,它应该被分派到正确的方法。 Why won't this work?
为什么这行不通?
public class Test {
public interface Shape {
}
static class Circle implements Shape {
}
static class Square implements Shape {
}
public void foo(Shape shape) {
Shape s = new Circle();
bar(s);
}
public void bar(Circle c) {
}
public void bar(Square s) {
}
}
You should be using Circle reference instead of Shape:您应该使用圆形参考而不是形状:
public void foo(Shape shape) {
Circle s = new Circle();
bar(s);
}
In method foo
variable s
is a Shape
class.在方法
foo
变量s
是一个Shape
类。 And your bar
methods expect only one of two : Circle or Square.而您的
bar
方法只需要以下两种方法之一:Circle 或 Square。
Your code would work if you create a method that receives a Shape如果您创建一个接收 Shape 的方法,您的代码将起作用
public void bar(Shape c) {
}
But because it is missing, the compiler throws an exception.但是因为缺少,编译器抛出异常。
To above method you could pass references of: Shape, Circle and Square.对于上述方法,您可以传递以下对象的引用:Shape、Circle 和 Square。 But then you will end up with a single method for all shapes.
但是你最终会得到一个适用于所有形状的方法。
If you know the class only in the runtime, then you need to do some casting:如果你只在运行时知道这个类,那么你需要做一些转换:
public void foo(Shape shape) {
Shape s = new Circle();
if(Circle.class.isInstance(s)){
bar(Circle.class.cast(s));
} else if (Square.class.isInstance(s)){
bar(Square.class.cast(s));
}
}
Yes you are correct polymorphism will occur but at run-time
.是的,您是正确的,但在
run-time
会发生多态性。 At compile time it only knows the declaration
type.在编译时它只知道
declaration
类型。 So there should be the same type in the method argument.所以方法参数中应该有相同的类型。
You can change the method like below:您可以更改如下方法:
public void bar(Shape s) {
if(s instanceof Circle){
}else if(s instanceof Square) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.