简体   繁体   中英

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. And your bar methods expect only one of two : Circle or Square.

Your code would work if you create a method that receives a 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. 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 . At compile time it only knows the declaration type. 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) {

  } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM