What is the role of interfaces in Java?

Source: Internet
Author: User

"Interface is a specification," that's right.

"It would be easier to write the implementation method directly in this class," How do you ensure that the interface is implemented in a class? If more than one class implements the same interface, how does the program know that they are related?

Since it is not a class to achieve, it is that there are many places to use, and we need to unify the standards. Even some programming languages (OBJECT-C) have not called the interface interface, directly called protocol.

The goal of uniform standards is that we all know what this is, but don't know exactly how to do it.

For example:

I know comparable this interface is used to compare two objects, so how to compare?

Numbers have numeric comparisons, strings have a comparison of strings, and students (their own classes) have their own methods of comparison.

Then, in another code that is responsible for the ordering of objects (not necessarily numbers), you must compare two objects.

What are the types of these two objects?

Object A, B? Certainly not, a > B syntax like this cannot be compiled.

int A, b? Or not? In the beginning, it's not necessarily a number.

....

So, comparable is coming. He tells the compiler that a B two objects all satisfy the comparable interface, that is, they can be compared. Specifically, this procedure does not need to be known.

So, he needs some concrete implementations, the comparable interface has a method called CompareTo. Then this method is used to replace operators such as <, >.

This is because the operator is reserved for comparison with built-in types (integers, floating-point numbers) rather than a generalized comparison operation.

If you can understand an existing interface such as comparable in the JDK's own library, it is easy to understand why you need to use the interface when developing the program.

What is the role of interfaces in Java?

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.