What does it mean that for two classes there is the same API, but different implementations?

I am new to Java and object oriented programming and have difficulty with concepts. For homework, I need to write two different classes that have the same exact API, but run differently. What does it mean and how does it work?

+6
source share
4 answers

I'll show you. This is an example of two classes having the same api.

interface ISpeak { void sayHi(); } class Teacher implements ISpeak{ @Override public void sayHi() { System.out.println("Hi!I am a Teacher!"); } } class Student implements ISpeak{ @Override public void sayHi() { System.out.println("Hi!I am a Student!"); } } 
+3
source

The same API means that two classes contain an exact list of public methods (each of which has the same method names and method parameters, like the other classes). The implementation of these methods may be different in each class. In addition, each class can also have private methods that do not appear in another class, because private methods are not part of the API that the class exposes to its users.

An API is usually defined in Java by an interface, so two classes that have the same API usually implement the same interface.

+1
source

You asked for a simple language instead of "computer speak:"

The interface is similar to a contract. The contract may say that

  • Tell me your name (getName ())
  • Say what you value (getRank ())
  • Tell me your number (getNumber ())

The contract has a name (often ending in "capable" - observable, etc.). Let them say "Identifiable." If we declare that we are implementing a contract, we must fulfill all its requirements.

You could be human, and I could be a robot - different classes with different different characteristics and behavior.

 class Human extends Object implements Identifiable class Robot extends Object implements Identifiable 

A program can view us as very different objects. He can say that the robot must go and attach itself and charge. He can tell a person that he can do something that people can do. But he can ask any of them to identify themselves.

+1
source

In Java and the wider context of modern OOP, this means that two class es must implement the same interface , effectively allowing clients of these classes to depend on the abstraction provided by this interface, instead of the implementation details of these specific classes.

0
source

All Articles