delita
delita

Reputation: 1581

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) {

    }
}

Upvotes: 1

Views: 167

Answers (2)

Beri
Beri

Reputation: 11610

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));
   }
}

Upvotes: 2

Saurabh
Saurabh

Reputation: 943

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) {

  } 
}

Upvotes: 0

Related Questions