What does “implements” do on a class?

前端 未结 7 750
抹茶落季
抹茶落季 2020-12-22 18:51

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

相关标签:
7条回答
  • 2020-12-22 18:57

    You should look into Java's interfaces. A quick Google search revealed this page, which looks pretty good.

    I like to think of an interface as a "promise" of sorts: Any class that implements it has certain behavior that can be expected of it, and therefore you can put an instance of an implementing class into an interface-type reference.

    A simple example is the java.lang.Comparable interface. By implementing all methods in this interface in your own class, you are claiming that your objects are "comparable" to one another, and can be partially ordered.

    Implementing an interface requires two steps:

    1. Declaring that the interface is implemented in the class declaration
    2. Providing definitions for ALL methods that are part of the interface.

    Interface java.lang.Comparable has just one method in it, public int compareTo(Object other). So you need to provide that method.

    Here's an example. Given this class RationalNumber:

    public class RationalNumber
    {
        public int numerator;
        public int denominator;
    
        public RationalNumber(int num, int den)
        {
            this.numerator = num;
            this.denominator = den;
        }
    }
    

    (Note: It's generally bad practice in Java to have public fields, but I am intending this to be a very simple plain-old-data type so I don't care about public fields!)

    If I want to be able to compare two RationalNumber instances (for sorting purposes, maybe?), I can do that by implementing the java.lang.Comparable interface. In order to do that, two things need to be done: provide a definition for compareTo and declare that the interface is implemented.

    Here's how the fleshed-out class might look:

    public class RationalNumber implements java.lang.Comparable
    {
        public int numerator;
        public int denominator;
    
        public RationalNumber(int num, int den)
        {
            this.numerator = num;
            this.denominator = den;
        }
    
        public int compareTo(Object other)
        {
            if (other == null || !(other instanceof RationalNumber))
            {
                return -1; // Put this object before non-RationalNumber objects
            }
    
            RationalNumber r = (RationalNumber)other;
    
            // Do the calculations by cross-multiplying. This isn't really important to
            // the answer, but the point is we're comparing the two rational numbers.
            // And no, I don't care if it's mathematically inaccurate.
    
            int myTotal = this.numerator * other.denominator;
            int theirTotal = other.numerator * this.denominator;
    
            if (myTotal < theirTotal) return -1;
            if (myTotal > theirTotal) return 1;
            return 0;
        }
    }
    

    You're probably thinking, what was the point of all this? The answer is when you look at methods like this: sorting algorithms that just expect "some kind of comparable object". (Note the requirement that all objects must implement java.lang.Comparable!) That method can take lists of ANY kind of comparable objects, be they Strings or Integers or RationalNumbers.

    NOTE: I'm using practices from Java 1.4 in this answer. java.lang.Comparable is now a generic interface, but I don't have time to explain generics.

    0 讨论(0)
  • 2020-12-22 19:06

    An interface can be thought of as just a list of method definitions (without any body). If a class wants to implement and interface, it is entering into a contract, saying that it will provide an implementation for all of the methods listed in the interface. For more information, see http://download.oracle.com/javase/tutorial/java/concepts/

    0 讨论(0)
  • 2020-12-22 19:07

    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!";
        }
    }
    

    Both the Cat and Dog class implement the ISpeak interface.

    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());
      }
    

    The output for this loop would be:

    bark!
    meow!

    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.

    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.

    For example:

    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());  
      }
    }
    

    Now consider this code:

    //  Some code in other class
    
    List<Person> people = getPeopleList();
    
    Collections.sort(people);
    

    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.

    0 讨论(0)
  • 2020-12-22 19:08

    In Java a class can implement an interface. See http://en.wikipedia.org/wiki/Interface_(Java) for more details. Not sure about PHP.

    Hope this helps.

    0 讨论(0)
  • 2020-12-22 19:13

    It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface

    0 讨论(0)
  • 2020-12-22 19:14

    Interfaces are implemented through classes. They are purely abstract classes, if you will.

    In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:

    interface ImplementMeStrictly {
       public function foo($a, $b);
    }
    
    class Obedient implements ImplementMeStrictly {
       public function foo($a, $b, $c) 
          {
          }
    }
    

    will cause an error, because the interface wasn't implemented as defined. Whereas:

    class InheritMeLoosely {
       public function foo($a)
          {
          }
    }
    
    class IDoWhateverWithFoo extends InheritMeLoosely {
       public function foo()
          {
          }
    }
    

    Is allowed.

    0 讨论(0)
提交回复
热议问题