Java interface and Java Abstract class

Source: Internet
Author: User

Before learning the object-oriented design patterns, Java interfaces and abstract classes are vague and hard to understand. When I first learned the Java language, it was hard to understand why the concept of interfaces was required. Although multi-inheritance can be implemented, there is only a method name and no method body, how can I implement it? I can't get anything from it. Except for some method names, can I simply add these methods to a specific class? Why must we have the abstract class concept? Why can't I write this parent class as a specific class, and can't the Child class inherit from it? Why do you need to get an abstract class and abstract methods without method bodies? It's confusing to make them look like interfaces and classes. When I started to learn the Java design model and really walked into the door of object-oriented design, I found that my understanding of object-oriented design was so one-sided and superficial, there is no real understanding of the essence of the concept of face-to-face objects. To a certain extent, it is still affected by the process-oriented approach. I think that a class is created, even if it is object-oriented, it is actually driven by the process. Let me talk about my current understanding of Object-oriented thinking, which is not necessarily correct and comprehensive, but I think it is a little better than before. Object-oriented thinking, I think the most important thing is abstraction. The quality of a software design depends to a large extent on its overall architecture. The overall architecture is actually your abstract framework for the entire macro business, when the structure of the high-level abstraction layer representing the business logic is reasonable, you only need to consider some algorithms and specific business implementations. When you need to develop another similar project, your previous abstract layer may be able to be used again. In the face of image design, the focus of reuse should be the reuse of the abstract layer, instead of reusing a specific code block, do you suddenly feel that your understanding of reuse has increased? When it comes to abstraction, I can't help but mention the Java interfaces and Java Abstract classes that once gave me a headache. This is also the focus of this article. Since the focus of object-oriented design lies in abstraction, Java interfaces and Java Abstract classes will inevitably exist. Java interfaces and Java Abstract classes represent abstract types, which are the specific manifestations of the abstraction layer we need to propose. To improve the Reuse Rate of programs, increase the maintainability and scalability of programs, the OOP object-oriented programming must be interface-oriented and abstract-oriented, correctly Use interfaces and abstract classes as the top layers of your structural hierarchy. There are too many similarities between Java interfaces and Java Abstract classes, and there are too many special points. What exactly is the best place for Java interfaces and Java Abstract classes? By comparing them, you can find out. 1. The biggest difference between Java interfaces and Java Abstract classes is that Java Abstract classes can provide partial implementation of some methods, but Java interfaces cannot. This is probably the only advantage of Java Abstract classes, however, this advantage is very useful. For example, if a new method is added to an abstract class, all its subclasses will get this new method at once, and the Java interface cannot do this, if you add a new method to a Java interface, all classes that implement this interface cannot be compiled successfully, because you must make every class implement this method again, this is obviously a disadvantage of the Java interface. 2. The implementation of an abstract class can only be given by the subclass of this abstract class. That is to say, this implementation is in the hierarchy defined by the abstract class. Due to the single inheritance of the Java language, therefore, the efficiency of an abstract class as a type definition tool is greatly reduced. At this point, the advantages of the Java interface come out. Any class that implements the method specified by a Java interface can have the type of this interface, A class can implement any number of Java interfaces, so this class has multiple types. 3. From the 2nd point, it is not difficult to see that the Java interface is an ideal tool for defining the hybrid type. The mixed class indicates that a class has not only a primary type but also other secondary behaviors. 4. Combined with the advantages of abstract classes and Java interfaces in and, the classic design pattern came out: the Declaration type work is still undertaken by the Java interface, however, a Java Abstract class is provided and this interface is implemented. Other specific classes of the same abstract type can choose to implement this Java interface or inherit this abstract class, that is to say, in the hierarchy, the Java interface is at the top, followed by the abstract class. Ha, the biggest advantages of both of them can be brought to the extreme. This mode is the "Default adaptation mode ". This mode is used in Java APIs and all follow certain naming rules: Abstract + Interface Name. Java interfaces and Java Abstract classes exist for implementation and Inheritance of specific classes. If you want to write a specific class to inherit another specific class, then there is a big problem with your design. The Java Abstract class exists for inheritance, and its abstract method is to force the subclass to be implemented. Use Java interfaces and abstract Java classes to declare the types of variables, declare parameters as types, return methods, and convert data types. Instead of using a specific Java class to declare the type of the variable, the parameter is the type declaration, the return type description of the method, and the conversion of the data type. I think, if you don't even have an interface or an abstract class in your code, maybe I can say that you didn't use any design pattern at all. Any design pattern is inseparable from the abstraction, abstract and Java interfaces and abstract Java classes are inseparable. Understanding abstraction, understanding Java interfaces, and abstract Java classes should actually start to analyze problems with object-oriented ideas and solve the problems. First, let's clarify the differences between classes and objects. A class is a broad concept that represents a group with a common nature, and an object refers to a specific thing. For example, "man" is a class that represents all people on the Earth, while "Zhang San", "Li Si", and "Einstein" are objects of each other, or they are instances of the "person" class. In Java, we can define classes and create class objects. For example: // declare a class "human" class human {private string name; Public String getname () {return name;} public void setname (string value) {This. name = value ;}//......} create a class: Human human = new human (). Secondly, many people understand the object and object references. fuzzy reference is the handle of the object operated by the program, it is equivalent to a pointer in C and C ++. As mentioned above, the object is a real thing, such as the previous Code: Human human = new human (); after the program is executed here, the Java virtual machine creates a human object in the memory and assigns the reference of this object to the human variable. There are two steps: first create a human object, and then assign the reference of the created object to the human variable. If an object reference is declared, but the object is not assigned to it, the reference points to an empty object, or references an object that does not exist. If you want to access the object through this reference, a null pointer exception will be thrown, such as: Human human ;//...... human. setname ("Zhang San"); Next we will focus on the relationships between classes, abstract classes, interfaces, and inheritance. A lot of careful beginners will ask questions like this on the Forum: 1. Interface implementation methods, but I can call the interface method in the program. Why? For example, connection, statement, and resultset in the Java. SQL package are all interfaces. How can we call them? 2. abstract classes cannot be instantiated, but JDK has many abstract class objects. Why? For example, system. In is an inputstream object, but inputstream is an abstract class. How can we get its object? In any case, you should understand that both abstract methods in the abstract class and methods defined in the interface need to be called. Otherwise, these methods are meaningless. It may not be mentioned in many books, or the readers do not notice this: if a subclass inherits its base class, it indicates that this class is also a type of its base class, an object of this subclass is a subclass type and also an object of its base class. It also has the type of its base class. If a class implements an interface, indicates that an object of this class is also an object of this interface. It may not be easy to understand. It is also a subclass, base class, type, interface or something, and it is easy to confuse. In fact, for a realistic example, you will think it is actually very simple: if "person" is a base class, "man" is a sub-class of "person. If "Zhang San" is a "man", that is, "Zhang San" is a "man" object, then it is clear that "Zhang San" is also an object of the "man" base class. By understanding this, we can easily understand why we can get abstract class objects: the original abstract class object is actually an object of its subclass or descendant class that has implemented the abstract method, but we use it as the base class of its abstract class. For example, "people", everyone will be "sad". When a man is sad, smoking, drinking, and crying when a woman is sad. Because different sub-classes perform different actions in "Sorrow", this action (method) is not implemented in the base class, but this method is required in the base class. Therefore, the "person" class can define an abstract method "Sorrow", and its sub-classes "man" and "woman" can implement the "Sorrow" method. However, the caller only treats the objects of men and women as one of their base class "people" and calls its "Sorrow" method. You can try out the JDK abstract class Java. lang. process: runtime = rumtime. getruntime (); Process = rumtime.exe C ("notepad.exe"); Class CLS = process. getclass (); system. out. println (CLS. getname (); the name of the Process class is printed. In Windows, it is a name similar to * Win32 * and a subclass of process. Because the process class is used to manage opened processes and has different implementations on different operating systems, it defines a method as an abstract method of process, specific operations can only be implemented by sub-systems corresponding to different operating systems. Next we will talk about interfaces. We know that interfaces only define some methods, but do not implement these methods. In fact, an interface is a specification that specifies what to do to implement this interface, or specifies the required capabilities (that is, methods) of the class that implements the interface ). Then we can make a comparison: a certain type of driver's license requires that people who get this driver's license must be able to drive a car or a bus ". So we think this driver's license is an interface, which specifies the capabilities required to implement its class. We can define a class driver that inherits from human and then implement the "Driver license holder" interface: public interface driverholder {public void drivercar (); Public void driverbus ();} public class driver extends human implements driverholder {public void drivercar (){//......} public void driverbus (){//......}} in this way, a "driver" object is also a drivreholder object. That is, a driver is also the object of a driver's license holder. In the program, we can do this: driverholder = new driver (); driverholder. drivercar (); this explains why "the interface has no implementation method but can get the Interface Class Object. In this case, some people may ask: why do we need to define an interface? Why don't we directly define this method in the driver class, and then driver = new driver (); it is much easier to call its drivercar (); and driverbus () methods? This is because Java is single-inherited and can only inherit from one class, so its type is limited to its base class or the base class of the base class. But Java can implement multiple interfaces, so that it can have multiple interface types. Just like a person, it inherits from the "spine" class, while "spine" inherits from the "animal" class. Therefore, "Michael" is an individual, he is a "spine", and of course he is also an "animal ". However, he can inherit many interfaces. For example, after obtaining a driver's license, he is a "Driver's license holder" type. He can also take the English level 6 certificate, so that he is a Level 6 certificate holder and so on. After understanding this, let's take a look at the Java event mechanism. The Java. AWT. Button class has an addactionlistener (actionlistener L); method. This method is passed in as an interface type: actionlisterner. In practice, we need to implement the actionlistener interface and pass in the object reference of the class that implements this interface as a parameter. In this way, the button object gets an actionlistener object, which knows that this actionlistener object has an actionreceivmed method, or that it can process Action events. When an Action event occurs, it can call the actionreceivmed method of this object. For example, we usually do this: public class testbutton extends frame implements actionlistener {private button btn1 = new button ();//...... public testbutton () {BTN. addactionlistener (this); this. add (BTN);} public void actionreceivmed (actionevent e) {}} now we assume that actionlistener is not an interface, but a class. Therefore, we can only inherit the actionlistener class and override the actionreceivmed method. However, Java is a single inheritance. If the class inherits the actionlistener class, it cannot inherit other classes (frame class) instead of the frame class, how to create a form and put the button in the form? In fact, the interface is not completely designed to solve Java's single inheritance problem. To some extent, it can achieve the separation of call and implementation details. For example, China's electricity usage specification is an interface: average voltage of 220 V, 50Hz, sin AC, Hydraulic Power Plant, thermal power plant, nuclear power plant, if a small diesel generator generates electricity according to this specification, it indicates that it has implemented the interface of this civil power source. refrigerators, televisions, washing machines, and other household appliances use these power supplies, indicates that they are calling this interface. Here, no matter where the electricity comes from, as long as it complies with the specifications of the civil power supply, the power supply also no matter what the electricity is used for, just provide power. Let's look at the event mechanism of the button. You need to know that the button should ensure that when all action events occur, the programmer can handle them in his code, library management system, cash register system, purchase, inventory, and so on. The interface can achieve this: Find a class to implement the actionlistener interface, and let the button get the reference of the Class Object (call the addactionlistener method), so that when the action event occurs, the button creates an actionevent that contains the event information, and then calls the method of this interface object to process the event. This is the class that implements the interface. Here, the button does not know exactly what the actionreceivmed method has done, nor should it know. The button is completely separated from the specific business logic. It can be applied to all occasions.
Related Article

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.