“实施”是什么上课吗? [英] What does "implements" do on a class?

查看:102
本文介绍了“实施”是什么上课吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类实现另一个类......那意味着什么?我找到了这个代码示例: http://www.java2s.com/Code/Php /Class/extendsandimplement.htm

If a class implements another class... what does that mean? I found this code sample: http://www.java2s.com/Code/Php/Class/extendsandimplement.htm

但遗憾的是它没有任何解释......

But unfortunately it doesn't have any explanation with it...

推荐答案

实现意味着它接受接口指定的指定行为。请考虑以下界面:

Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:

public interface ISpeak
{
   public String talk();
}

public class Dog implements ISpeak
{
   public String talk()
   {
        return "bark!";
   }
}

public class Cat implements ISpeak
{
    public String talk()
    {
        return "meow!";
    }
}

Cat Dog 类实现 ISpeak 界面。

接口有什么好处,我们现在可以通过 ISpeak 接口引用这个类的实例。请考虑以下示例:

What's great about interfaces is that we can now refer to instances of this class through the ISpeak interface. Consider the following example:

  Dog dog = new Dog();
  Cat cat = new Cat();

  List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();

  animalsThatTalk.add(dog);
  animalsThatTalk.add(cat);

  for (ISpeak ispeak : animalsThatTalk)
  {
      System.out.println(ispeak.talk());
  }

此循环的输出为:


树皮!

喵!

bark!
meow!

接口提供了一种基于它们的东西以通用方式与类交互的方法em> do 而不暴露实现类是什么。

Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.

例如,Java中最常用的接口之一是 可比较 。如果您的对象实现了此接口,您可以编写一个消费者可以用来对对象进行排序的实现。

One of the most common interfaces used in Java, for example, is Comparable. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.

例如:

public class Person implements Comparable<Person>
{
  private String firstName;
  private String lastName;

  // Getters/Setters

  public int compareTo(Person p)
  {
    return this.lastName.compareTo(p.getLastName());  
  }
}

现在考虑以下代码:

//  Some code in other class

List<Person> people = getPeopleList();

Collections.sort(people);

此代码所做的是为上课。因为我们实现了 Comparable 接口,所以我们能够利用 Collections.sort()方法对我们的<$进行排序c $ c>列出 对象按其自然顺序排列,在本例中为姓氏。

What this code did was provide a natural ordering to the Person class. Because we implemented the Comparable interface, we were able to leverage the Collections.sort() method to sort our List of Person objects by its natural ordering, in this case, by last name.

这篇关于“实施”是什么上课吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆