E
E
EVGENY T.2019-07-26 12:57:32
Java
EVGENY T., 2019-07-26 12:57:32

Why use interface a not abstract class?

In examples for courses and books, where OOP patterns and frameworks are discussed, interfaces of this type are used almost everywhere:
interface Button;
class MyButton implements Button;
Those. abstraction is meant, but the interface mechanism is used. Why?
It looks more logical like this:
abstract class Button;
class MyButton extends Button;
And then use interfaces like Clickable.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Denis Zagaevsky, 2019-07-26
@zagayevskiy

The question was posed incorrectly.
Firstly, what the author of this or that book had in mind is known only to him, and if it is not clear from the book, then there are two options - either the book sucks, or you are not ready to read this book.
Secondly, the statement "abstraction is meant, but the interface mechanism is used" is incorrect. Interfaces in Java are one of the mechanisms for building abstractions.
Neither the first nor the second examples seem logical. Interfaces without methods (marker interfaces) are used quite rarely and in specific situations (an example is java.util.RandomAccess, which marks free access to an arbitrary element of a collection).
An abstract class without state and methods is not needed at all, as it will complicate the development of the user of this class.

M
Mercury13, 2019-07-26
@Mercury13

Both the first and the second have the right to life.
The second one is really used more often: we have a ready-made or semi-finished button, and we need to add the functionality of Our Cool Button ™ to it. Also, words like Clickable are better suited for interface names than Button.

class Button {
  protected void paint(Canvas aCanvas) {}
}

class MyButton extends Button {
  @Override
  protected void paint(Canvas aCanvas) {}
}

And the first - for example, we want to work with Our Cool Button ™ as with a button of unknown functionality, which can only be pressed and tell what state it is in.
interface Button {
  void press();
  boolean state();
  void addListener(ButtonListener x);
}

class GameObject {
  void paint(Renderer renderer);
}

class MyButton extends GameObject implements Button {
}

class FridgeGame implements ButtonListener {  // помните, такая была в «Братьях Пилотах»?
  Button buttons[][] = new MyButton[4][4];  
}

S
sergey, 2019-07-26
kuzmin @sergueik

in java, a class can implement more than one interface

interface A {
}

interface B {
}

class X implements A, B {
}

but only one superclass
class X extends Y {
}

and for example annotations are interfaces
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question