简体   繁体   中英

What does it mean for two classes have the same API but different implementations?

I am a beginner to Java and object-oriented programming and having some difficulty with the concepts. For homework, I need to write two different classes that have the same exact API but are implemented differently. What does that mean and how does that work?

I will show you.This is an example that two class have 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!");
    }
}

Same API means the two classes contain the exact same list of public methods (each having the same method name and method parameters as the other class). The implementation of these methods can be different in each class. In addition, each class can also having private methods that don't appear in the other class, since private methods are not part of the API that a class provides to its users.

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

You asked for plain language instead of "computer speak:"

An interface is like a contract. The contract may say we have to

  1. Tell me your name (getName())
  2. Tell me you rank (getRank())
  3. Tell me your number (getNumber())

The contract has a name (quite often ending in "able" - observable, etc.) Let's say Identifiable. If we declare that we implement the contract we must fulfil all of its requirements.

You could be a human and I could be a robot - different classes with other different characteristics and behaviour.

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

The program can treat us as very different objects. It can tell the robot to go and dock itself and charge. It can tell the human to do something only humans can do. But it can ask either of them to identify themselves.

在Java和现代OOP的更广泛的上下文中,它意味着两个class应该实现相同的interface ,有效地允许这些类的客户端依赖于该接口提供的抽象而不是那些具体类的实现细节。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM