Application of Java object-oriented interface

Source: Internet
Author: User

Brief introduction

Some concrete applications of abstract classes in object-oriented theory have been said. Today I'm talking about another key thing in object-oriented theory. Interface. Abstract classes are classes, and interfaces are special abstract classes. Why spend so much time studying abstract classes and interfaces? Because there are only two theories that we have mastered and understood. It's going to work. Can greatly improve the scalability and maintainability of the program. In the future to learn what design mode is a layer of window paper a stab on the broken.

Concept Java interface is a series of methods of Declaration, is a collection of methods features, an interface only the method of the characteristics of the method is not implemented, so these methods can be in different places by different classes implementation, and these implementations can have different behavior (function). Two meanings: (concept excerpt from Baidu Encyclopedia)
    1. Java interface, the structure that exists in theJava language , has a specific syntax and structure;
    2. A collection of features of the methods that a class has, is a logical abstraction. The former is called "Java Interface", which is called "interface".

I personally understand that the interface and the slogan of the specific work on the slogan by the following people to complete

For example, a leader at a meeting said to his people, our company wants to develop a run to calculate Carlo's bracelet, the final result can be displayed on the phone. Bluetooth technology is used for mobile phone and Bluetooth connection.

That's the slogan. The specific phone Bluetooth how to connect with the bracelet, the data how to display on the phone and so on technical issues, leadership is not closed. These jobs are mainly done by the men. In terms of object-oriented theory, this is the interface.

Interface, English is called interface, in software engineering, the interface refers to the method or function for others to call. From here, we can realize the original intention of the Java language Designer, which is the abstraction of the behavior. In Java, the form of an interface is as follows:

Syntax format:
[public] Interface Person {    abstractvoidthrows  exception;//abstract method, the specific function is done by subclass}

Does everyone think that the interface is much like the abstract class that was said earlier? Yes. Interfaces and abstract classes. There are too many similarities, and there are too many different places. Many people think they can be used interchangeably when they are beginners, but not in practice.

Abstract classes are classes, interfaces are interfaces

To put it simply: subclasses of an abstract class can no longer inherit other classes, and multiple interfaces may be implemented. Because Java is single-inheritance.

When talking about interfaces, abstract classes are indispensable. If alone to speak, loses its essence of content. Some of the training centers of the teachers in the explanation, is a separate example of the explanation. Very deceptive.

Let me take an example to illustrate how interfaces and abstract classes are used in real-world development.

Remember that object-oriented programming, in fact, is interface-oriented programming. Java is single-inheritance, but multiple interfaces can be implemented. This is the magic of Java code. Many design patterns also take advantage of this.

Example sub-analysis:

For example, dogs, rabbits and fish are the three animals .

According to what I said earlier. We will soon be able to design the abstract class. It doesn't matter if it doesn't. In the combination of what we say with Baidu to see again.

1  Public Abstract classAnimal {2          Public Abstract voidBreathing ();//Breathing3          Public Abstract voidEat ();//Eat4          Public Abstract voidSwimming ();//Swimming5}

The abstract class has. We are now designing three subcategories of dogs, rabbits and fish.

1  Public classDogextendsAnimal {2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("The Master gave me bones to eat.")); One     } A  - @Override -      Public voidswimming () { theSystem.out.print ("Nice swimming"); -     } -}
1  Public classFishextendsAnimal {2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("I'm eating."); One     } A  - @Override -      Public voidswimming () { theSystem.out.print ("The water feels So good"); -     } -}

The last is the Rabbit class.

1  Public classRabbitextendsAnimal {2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("The carrot is so delicious"); One     } A  - @Override -      Public voidswimming () { theSystem.out.print ("5555555555555, I can't swim"); -     } -}

Found the problem, the rabbit can't swim, because it is the inheritance of the relationship. In the future, every animal will have to rewrite the swimming method, whether or not to swim. You know, not every animal can swim.

What to do. Some people say that in writing a swimming function class, let it inherit. Pro-Java only supports single inheritance and does not support multiple inheritance, but but what? can support multiple interfaces. Here we don't need so many interfaces one is enough.

First change the code of the abstract class

1  Public Abstract class Animal {2          Public Abstract void Breathing (); // Breathing 3          Public Abstract void Eat (); // Eat 4 }

What about the swimming function? We write an interface separately

1  Public Interface Animalbehavior {2      Public Abstract void Swimming (); // Swimming 3 }

So how do we do that? We'll change the dog and fish sub-category above.

1  Public classDogextendsAnimalImplementsanimalbehavior{2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("The Master gave me bones to eat.")); One     } A  - @Override -      Public voidswimming () { theSystem.out.print ("Nice swimming"); -     } -}
1  Public classFishextendsAnimalImplementsAnimalbehavior {2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("I'm eating."); One     } A  - @Override -      Public voidswimming () { theSystem.out.print ("The water feels So good"); -     } -}

Rabbit Type

1  Public classRabbitextendsAnimal {2 3 @Override4      Public voidbreathing () {5System.out.print ("It feels good to breathe the air");6     }7 8 @Override9      Public voidEat () {TenSystem.out.print ("The carrot is so delicious"); One     } A}
The difference between an abstract class and an interface

There are so many similarities between Java interfaces and Java abstract classes, and there are so many special places, where exactly is the best place for them? Compare them and you'll find out.

One of the biggest differences between Java interfaces and Java abstract classes is that Java abstract classes can provide partial implementations of some methods, while Java interfaces cannot (that is, only methods can be defined in the interface, but not the implementation of methods, but in the abstract Class can have both the specific implementation of the method, and there is no concrete implementation of the abstract method, which is probably the only advantage of Java abstract class, but this advantage is very useful. If you add a new concrete method to an abstract class, all of its subclasses get the new method all of a sudden, and the Java interface does not do this, and if a new method is added to a Java interface, all classes that implement the interface will fail to compile successfully. Because you have to let every class implement this method again, this is obviously a disadvantage of the Java interface. This is a similar issue in one of my other blog MapReduce new and old API differences, where the new MapReduce API tends to use abstract classes rather than interfaces because it's easier to extend. The reason is that the underlined part says.

The implementation of an abstract class can only be given by subclasses of this abstract class, that is, the implementation is in the hierarchy of inheritance defined by the abstract class, and because of the single inheritance of the Java language, the efficiency of the abstract class as a type definition tool is greatly compromised. At this point, the advantages of the Java interface come out that any class that implements a method specified by a Java interface can have the type of this interface, and a class can implement any number of Java interfaces, so there are many types of this class. (with abstract classes, the subclass type that inherits this abstract class is relatively single, because subclasses can only inherit abstract classes, whereas subclasses can implement multiple interfaces at the same time because the types are more numerous.) Interfaces and abstract classes can define objects, but only their specific implementation classes are instantiated. )

From the 2nd, it is not difficult to see that Java interfaces are an ideal tool for defining mixed types, and mixed classes indicate that a class does not only have the behavior of one of the main types, but also has other minor behaviors.

Combining the advantages of abstract class and Java interface in 1, 2 points, the design pattern of the refined code comes out: the work of declaring type is still assumed by the Java interface, but at the same time it gives a Java abstract class, and implements this interface, and other specific classes belonging to this abstract type can choose to implement this Java interface , you can also choose to inherit this abstract class, that is, in the hierarchy, the Java interface at the top, followed by the abstract class, the next two of the greatest advantage can be played to the extreme. This mode is "default adaptation mode". This pattern is used in the Java language API, and all follow a certain naming convention: Abstract + interface name. (A extends ABSTRACTB implements INTERFACEC, then a can choose to implement (@Override) interface Interfacec in the method, you can choose not to implement; a you can choose to implement (@Override) Abstract class Abstractb method, can also choose not to implement)

Inheritance is a "yes" relationship, while an interface implementation is a "no" relationship. If a class inherits an abstract class, the subclass must be the kind of abstract class, and the implementation of the interface is whether or not there is a relationship that does not exist, such as if the bird can fly (or if there is no flight)

sentiment

Simple business design is easy and complex business wants to design it according to the object-oriented theory. Need some experience to our technical tireless pursuit. And in-depth understanding of the business. Software development don't think it's about writing code. In fact, it is full of wisdom and challenge.

If you are unfamiliar with the business process you are developing. Your design pattern is better, you will feel the impossible. When you are familiar with the business, design patterns are also proficient. You must be a leader in that field. It's not your job to know the architect in the future.

The statement reads as follows:
    1. Learning to solve problems with object-oriented thinking is a good habit as a programmer.
    2. Technology is endless, learning is endless. I just play a role in getting started and starting out.
    3. Because I have a lot of work to do. Writing this is mainly in the use of spare time. Inevitably the code has the wrong place. Or a typo in the text. Or this sentence, write these are mainly to teach you how to learn. Theory holds, language is just a tool. Thank you for your busy schedule to watch this article.
    4. The code is implemented in this article and has been tested:
    5. I write the content can be reproduced casually, welcome to reprint.

Application of Java object-oriented 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.