Using an interface as a Type

Source: Internet
Author: User

When you define a new interface, you are defining a new reference data type. you can use interface names anywhere you can use any other data type name. if you define a reference variable whose type is an interface, any object you assign to itMustBe an instance of a class that implements the interface.

As an example, here is a method for finding the largest object in a pair of objects,AnyObjects that are instantiated from a class that implementsRelatable:

public Object findLargest(Object object1, Object object2) {   Relatable obj1 = (Relatable)object1;   Relatable obj2 = (Relatable)object2;   if ((obj1).isLargerThan(obj2) > 0)      return object1;   else       return object2;}

By castingobject1ToRelatableType, it can invokeisLargerThanMethod.

If you make a point of implementingRelatableIn a wide variety of classes, the objects instantiated fromAnyOf those classes can be compared withfindLargest()Method-provided that both objects are of the same class. Similarly, they can all be compared with the following methods:

public Object findSmallest(Object object1, Object object2) {   Relatable obj1 = (Relatable)object1;   Relatable obj2 = (Relatable)object2;   if ((obj1).isLargerThan(obj2) < 0)      return object1;   else       return object2;}public boolean isEqual(Object object1, Object object2) {   Relatable obj1 = (Relatable)object1;   Relatable obj2 = (Relatable)object2;   if ( (obj1).isLargerThan(obj2) == 0)      return true;   else       return false;}

These methods work for any "relatable" objects, no matter what their class inheritance is. When they implementRelatable, They can be of both their own class (or superclass) type andRelatableType. This gives them some of the advantages of multiple inheritance, where they can have behavior from both a superclass and an interface.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.