0

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.
  }
}
4
  • 1
    Well, what's the error? Commented Jun 2, 2014 at 3:06
  • I'm not sure it's just saying line 16 can't run Commented Jun 2, 2014 at 3:07
  • 3
    If you're using any decent IDE, the compiler error has got to give more information than that... Commented Jun 2, 2014 at 3:09
  • even the command line compiler will give a lot more information... Commented Jun 2, 2014 at 3:10

1 Answer 1

5
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();
Sign up to request clarification or add additional context in comments.

2 Comments

Because there is a method press() in the interface Button.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.