0

I was wondering if it's possible to define a method within the implementation of an interface class and call that method from another class?

for example:

public interface MyInterface
{
    void method1();
}
public class MyClass1 implements MyInterface
{
    public void method1()
    {
        System.out.println("This is already defined in MyInterface")
    }

    public void method2()
    {
        System.out.println("This is not already defined in MyInterface")
    }
}
public class MyClass2
{
    public static void main(String[] args) {
    {
        MyInterface interface = new MyClass1()
        interface.method2

    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    What happens when you try to do this? Does your code compile? Run? Behave as expected? – Hovercraft Full Of Eels Feb 15 '20 at 19:39
  • You need to understand what the compiler sees when it looks at a variable. The type of the variable is the *declared* type, not the reference type. – Hovercraft Full Of Eels Feb 15 '20 at 19:40
  • Also, please have a look at [why can't I call a subclass method using a reference of a parent type that refers to an instance of a sub-type?](https://stackoverflow.com/questions/32283961/why-cant-i-call-a-subclass-method-using-a-reference-of-a-parent-type-that-refer) – Hovercraft Full Of Eels Feb 15 '20 at 19:43
  • Also, what happens when you instead try `((MyClass1) interface).method2();`? – Hovercraft Full Of Eels Feb 15 '20 at 19:44
  • I get a java: cant find symbol error when I try to compile. Also, I cannot use ((MyClass1) interface).method2() either as the interface has 3 different implementations in 3 different classes so I would have to specify which implementation I'm using each time which defeats the purpose of an interface. – luke Phillips Feb 15 '20 at 20:26
  • I'm not suggesting that you do the casting, but rather only that this is what would be required to get the posted code to work. Hopefully, though you are learning now how Java inheritance works, the difference between a type and an object, why the code you've posted doesn't work and perhaps how to fix your code so that it works the way you desire. – Hovercraft Full Of Eels Feb 15 '20 at 20:38

0 Answers0