I can't understand why I'm getting an error on the line indicated below. if there is a specific topic which covers it please provide a line (or an explanation).
public interface Button {
void press();
}
public class Bomb implements Button {
public void press() {
System.out.println("Doesn't work");
}
void boom() {
System.out.println("Exploded");
}
}
public class Test {
public static void main(String[] args) {
Button redButton = new Bomb();
redButton.press();
redButton.boom(); // <-- Error is on this line.
}
}
Elliott Frisch
202k20 gold badges166 silver badges265 bronze badges
-
1Well, what's the error?awksp– awksp2014年06月02日 03:06:49 +00:00Commented Jun 2, 2014 at 3:06
-
I'm not sure it's just saying line 16 can't runuser3550204– user35502042014年06月02日 03:07:54 +00:00Commented Jun 2, 2014 at 3:07
-
3If you're using any decent IDE, the compiler error has got to give more information than that...awksp– awksp2014年06月02日 03:09:31 +00:00Commented Jun 2, 2014 at 3:09
-
even the command line compiler will give a lot more information...Thilo– Thilo2014年06月02日 03:10:58 +00:00Commented Jun 2, 2014 at 3:10
1 Answer 1
Button redButton = new Bomb();
The interface Button does not define a method boom().
The runtime instance may be a Bomb (which has boom()), but the compiler does not know that (it only sees the compile time type, which is Button).
You need to use the interface defined by class Bomb:
Bomb redButton = new Bomb();
answered Jun 2, 2014 at 3:08
Thilo
264k107 gold badges527 silver badges674 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Thilo
Because there is a method
press() in the interface Button.Sal Prima
Interface have different concept compared to Inheritance (Super class & Sub class). Interface is used when you need several different implementations of the same method name. In the real life opening coke bottle vs opening the door have different ways, so you need same method name which is open() but the way of opening its different in the other hand, when you need same ways with exactly same method name you may use Inheritance. CMIIW.
lang-java