public interface MyInterface {} public class A implements MyInterface{} public class B implements MyInterface{} public class Tester { public static void main(String[] args){ MyInterface a = new A(); MyInterface b = new B(); test(b);
You are trying to pass the object referenced by the MyInterface reference variable to the method specified by the argument with its subtype of type test(B b) . The compiler complains here because the reference variable MyInterface can refer to any object that is a subtype of MyInterface , but is not necessarily an object of B There may be runtime errors if allowed in Java. Take an example that will make the concept clearer for you. I changed your code for class B and added a method.
public class B implements MyInterface { public void onlyBCanInvokeThis() {} }
Now just change the test(B b) method as shown below:
public static void test(B b){ b.onlyBCanInvokeThis(); System.out.println("B"); }
This code will explode at runtime, if allowed by the compiler:
MyInterface a = new A();
To prevent this, the compiler forbids such method invocation methods using superclass references.
I'm not sure what you are trying to achieve, but it looks like you want to achieve polymorphism at runtime. To do this, you need to declare a method in MyInterface and implement it in each subclass. Thus, a method call will be resolved at runtime based on the type of the object, not the reference type.
public interface MyInterface { public void test(); } public class A implements MyInterface{ public void test() { System.out.println("A"); } } public class B implements MyInterface{ public void test() { System.out.println("B"); } } public class Tester { public static void main(String[] args){ MyInterface a = new A(); MyInterface b = new B(); b.test();
source share