简体   繁体   English

两个类具有相同的API但实现不同意味着什么?

[英]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. 我是Java和面向对象编程的初学者,对概念有些困难。 For homework, I need to write two different classes that have the same exact API but are implemented differently. 对于家庭作业,我需要编写两个具有相同API的不同类,但实现方式不同。 What does that mean and how does that work? 这是什么意思,它是如何工作的?

I will show you.This is an example that two class have same api. 我会告诉你。这是两个班级有相同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). 相同的API意味着这两个类包含完全相同的公共方法列表(每个方法具有与另一个类相同的方法名称和方法参数)。 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. 此外,每个类还可以具有不出现在其他类中的私有方法,因为私有方法不是类向其用户提供的API的一部分。

An API is usually defined in Java by an interface, so two classes that have the same API will usually implement the same interface. API通常由Java定义,因此具有相同API的两个类通常会实现相同的接口。

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()) 告诉我你的名字(getName())
  2. Tell me you rank (getRank()) 告诉我你排名(getRank())
  3. Tell me your number (getNumber()) 告诉我你的号码(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 ,有效地允许这些类的客户端依赖于该接口提供的抽象而不是那些具体类的实现细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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