I have an interface and three classes. In class B
, I define a method called printHello
. Then, in class Test
, I declare a new IHello
object and assign it to a new B.
The problem is, the code does not compile, because I get an error indicating "The method printHello() is undefined for type IHello". This is confusing to me, because I am able to assign an object of type IHello
to a new B
, so shouldn't that object be able to use B
's methods even if the interface does not have them?
To solve this problem, I understand I could either declare a method called printHello
in the IHello
interface, or I could declare the object of type B instead. Is there anything else I could do to solve the problem?
Interface IHello
public interface IHello {
void hello();
}
Class A
public class A implements IHello{
public void hello(){
System.out.println("hello");
}
}
Class B
public class B extends A {
public void printHello(){
this.hello();
}
}
Class Test
public class Test {
public static IHello b;
public static void main(String[] args) {
b = new B();
b.printHello(); //The method printHello() is undefined for type IHello
}
}