Difference between abstract class and interface in Java and C #

Source: Internet
Author: User
Tags define abstract

(Source http://hi.baidu.com/dgx_lsyd3/blog/item/8f710ed7ca49badda144dfd0.html)


---------------------------------------------
Explanation 1:

Abstract class and interface are two mechanisms supported for the definition of abstract classes in Java. It is precisely because of the existence of these two mechanisms that give Java powerful object-oriented capabilities. Abstract class and Interface
Therefore, many developers have great similarities in the support for abstract class definitions and can even replace them.
The interface is relatively casual. In fact, there is a big difference between the two. Their choice even reflects the understanding of the nature of the problem domain and the understanding of the design intent.
True and reasonable. This article will analyze the differences between them and try to provide developers with a basis for selection between them.

Understanding abstract classes:

Abstract class and interface are used for abstract classes in Java language (abstract classes in this article are not translated from abstract class, it
Abstract class is a method used to define abstract classes in Java. Be careful when defining abstract classes.
What benefits can it bring to us?

In the concept of object-oriented, we know that all objects are depicted through classes, but this is not the case. Not all classes are used to depict objects. If a class does not contain enough information
Class is an abstract class. Abstract classes are often used to represent the abstract concepts we have come up with in the analysis and design of problem domains. They look different to a series, but are essentially the same.
. For example, if we develop a graphic editing software, we will find that some specific concepts such as circles and triangles exist in the problematic field. They are different, but they all belong to shapes.
The concept of shape does not exist in the field of problem. It is an abstract concept. It is precisely because abstract concepts do not have specific concepts in the problem field that are used to characterize abstract concepts.
It cannot be instantiated.

In the Object-Oriented field, abstract classes are mainly used to hide types. We can construct a fixed abstract description of a group of actions, but this group of actions can have any specific implementation method. This abstract description
Abstract class, and any possible implementations of this group are all possible Derived classes. The module can operate on an abstract body. Because the module depends on a fixed abstract body, it can be repair-prohibited.
Also, the behavior function of this module can be extended by deriving from this abstract body. Readers familiar with OCP must know that, in order to realize a core principle of object-oriented design, OCP (open
-Closed principle), the abstract class is the key.

Abstract class and interface:

At the syntax level, the Java language provides different definitions for abstract class and interface. The following describes how to define an abstract class named demo.

You can use abstract class to define a demo abstract class as follows:

Abstract class demo
{
Abstract void Method1 ();
Abstract void method2 ();
...
}

The following method is used to define the demo abstract class using the interface:

Interface demo
{
Void Method1 ();
Void method2 ();
...
}

In the abstract class method, the demo can have its own data members or non-Abstarct member methods. In the implementation of the interface method,
Demo can only have static data members that cannot be modified (that is, they must be static final, but generally do not define data members in the interface ).
Methods are abstract. In a sense, interface is a special form of abstract class.

From the programming point of view, abstract class and interface can be used to implement the idea of "Design by contract. However, there are some differences in usage.

Abstract class represents an inheritance relationship in Java. A class can only use an inheritance relationship once. However, a class can implement multiple interfaces. Maybe this is a compromise between Java designers and Java's support for multi-inheritance.

Secondly, in the definition of abstract class, we can assign the default behavior of the method. However, in the interface definition, a method cannot have default behavior. to bypass this restriction, you must use a delegate. However, this increases complexity and sometimes causes great trouble.

Another serious problem still exists when the default behavior cannot be defined in the abstract class, which may cause maintenance trouble. Because if you want to modify the interface of the class later (usually through
Abstract class or interface is used to adapt to new situations (for example, it is very troublesome to add new methods or add new parameters to used methods,
It may take a lot of time (especially when there are many derived classes ). However, if the interface is implemented through abstract class, you may only need to modify the definition in
The default behavior in abstract class is enough.

Similarly, if the default behavior cannot be defined in the abstract class, the same method will appear in every derived class of the abstract class, in violation of the "one rule, one place" principle,
Code duplication is also not conducive to future maintenance. Therefore, be careful when selecting abstract class and interface.

Abstract class and interface from the design concept level

The difference between abstract class and interface is discussed from the perspective of syntax definition and programming. The difference between these layers is relatively low-level and non-essential. This section will
One level: abstract class and interface reflect the design concept to analyze the differences between the two. The author believes that the two concepts can be understood only through analysis at this level.
.

As mentioned above, Abstarct class represents an inheritance relationship in Java. To make the inheritance relationship reasonable, there must be a "is a" relationship between the parent class and the derived class,
That is to say, the concept of the parent class and the derived class should be essentially the same (for more information about the "is a" relationship in the references [3], for interested readers, refer ). For
The interface is not the same as the interface implementer and interface definition. It only implements the interface setting.
. In order to make the discussion easier to understand, we will explain it through a simple example below.

Consider this example. Suppose there is an abstract concept about the door in our problem field. The door has two actions: open and close, in this case, abstract class or interface can be used to define a type that represents the abstract concept. The definitions are as follows:

Use abstract class to define door:

Abstract class door {
Abstract void open ();
Abstract void close ();
}


Use the interface method to define the door:

Interface door {
Void open ();
Void close ();
}


For other specific door types, extends can use the door defined in abstract class or implements to use the door defined in interface mode. It seems that there is no big difference between abstract class and interface.

If you want the door to have the alarm function. How do we design the class structure for this example (in this example, we mainly want to demonstrate abstract class and
Interfaces are reflected in the differences in design concepts. Other irrelevant issues are simplified or ignored )? Below we will list possible solutions and introduce these different solutions from the design concept layer.
Line Analysis.

Solution 1:

Add an alarm method to the door definition as follows:

Abstract class door {
Abstract void open ();
Abstract void close ();
Abstract void alarm ();
}


Or

Interface door {
Void open ();
Void close ();
Void alarm ();
}


The alarmdoor with alarm function is defined as follows:

Class alarmdoor extends door {
Void open (){...}
Void close (){...}
Void alarm (){...}
}


Or

Class alarmdoor implements door {
Void open (){...}
Void close (){...}
Void alarm (){...}
}

This method violates a core principle ISP (interface segregation priciple) in object-oriented design.
The inherent behavior methods are mixed with the behavior methods of another concept "alarm. One problem is that the modules that rely solely on the door concept will
Changes (for example, modifying the parameters of the alarm method), and vice versa.

Solution 2:

Since open, close, and alarm belong to two different concepts, they should be defined in abstract classes that represent these two concepts according to the ISP principle. The two concepts are defined as follows:
Abstract class is defined. Both concepts are defined using the interface method. One concept is defined using abstract class and the other is defined using
Interface mode definition.

Obviously, because the Java language does not support multiple inheritance, both concepts are defined using abstract class. The latter two methods are feasible, but their selection reflects the understanding of the concept nature in the problem field, and whether the reflection of the design intent is correct and reasonable. Let's analyze and explain them one by one.

If both concepts are defined using the interface method, there are two problems: 1. We may not understand the problem field clearly. In essence, the concept of alarmdoor is
Door or alarm? 2. If we have no problem understanding about the problem field, for example, we have analyzed the problem field and found that alarmdoor is essentially consistent with door.
So we will not be able to correctly reveal our design intent in implementation, because the above meanings are not reflected in the definitions of these two concepts (both using the interface method.

If our understanding of the problem field is: alarmdoor is essentially a door in concept, it also has the alarm function. How can we design and implement it to clearly reflect what we mean?
What about it? As mentioned above, abstract class represents an inheritance relation in Java, and the inheritance relation is essentially a "is a" relation. So for the concept of door,
We should use the Abstarct class method for definition. In addition, alarmdoor has the alarm function, indicating that it can complete the behaviors defined in the alarm concept, so the alarm concept can be
It is defined in interface mode. As follows:

Abstract class door {
Abstract void open ();
Abstract void close ();
}
Interface alarm {
Void alarm ();
}
Class alarmdoor extends door implements alarm {
Void open (){...}
Void close (){...}
Void alarm (){...}
}


This implementation method can clearly reflect our understanding of the problem field and correctly reveal our design intent. Abstract class represents the "is a" relation,
The interface represents a "like a" relationship, which can be used as a basis for your selection. Of course, this is based on your understanding of the problem field. For example:
The concept of alarmdoor is essentially an alarm, and it also has the function of door, so the above definition method will be reversed.

Conclusion

Abstract class and interface are two methods of defining abstract classes in Java. They have great similarity. However, their choices often reflect
Understanding of the concept nature in the problem field, and whether the reflection of the design intent is correct and reasonable, because they represent the different relationships between concepts (although they can all implement the required functions ).

---------------------------------------------
Explanation 2:

Interface: Interface
Abstract class: abstract class
Class: class, including abstract classes.
Java learners, or oo programmers, need to figure out the differences between the two concepts.
Here I will talk about my point of view:

In OO, interface and abstract class are two different concepts:

1: abstract class is similar to abstract data
Type (abstract data type), which defines all the features that subclass (subclass) should have.
Declare methods and variables. For example, define an abstract type: vehicle. In Java, the abstract must be added to the class or method. For example:

Public abstract class car
{
Public int wheel;
Public abstract void mobile ();
}
// This abstract class declares the characteristics (such as wheels) and behaviors (such as moving) that all vehicles should have ). Then you can extend the abstract class extend, as long as it is a car, you can also add your own features in the subclass (subclass), such:

Public class sports car extends
{
Public void mobile ()
{
System. Out. println ("I'm moving ");
}
Public void engine type () // behavior of the self (sports car)
{
System. Out. println ("advanced engine ");
}

Wheel = 4;
}

Public class bicycle extends car
{
Public void mobile ()
{
System. Out. println ("I'm moving ");
}
Public void () // behavior of self (bicycle)
{
System. Out. println ("I Can't move ");
}
Wheel = 2;
}

2: interface is used to define a protocol, and all methods can implement it. An interface defines the method and final static
Static) variable. All things that implement this interface must be consistent with this interface.
The defined behavior is consistent. Using Interfaces allows objects to communicate with each other under certain specifications. For example:

Public interface TCP protocol
{
Public void open port ();
Public void close port ();
}
In this case, the two methods can be used for communication as long as the interface is implemented.

On the Java platform, there are three main differences:
1: A class can inherit only one super class, but multiple interfaces can be implemented.
2: In abstract class, you can have a non-abstract method, that is, a meaningful method, but the interface does not work.
For example:

Public abstract class car
{
Public int wheel;
Public abstract void mobile ();
Public String what am I ()
{
Return "car ";
}
}

3: The interface does not belong to the inheritance scope. That is, it is impossible to become a super class)

Note: This article is based on the q13 in Sun's FAQ: http://access1.sun.com/faqsets/newtojavatechfaq.html.
Translated.

There is another solution:
-----------------------------------

In C #, the interface is actually an abstract class. This should be to take care of C ++ developers. If we define an interface: interface iobserver, the corresponding Il is actually like this:

. Class interface public abstract auto ANSI iobserver
{
} // End of class iobserver

If we define an abstract class: public abstract class cabstract, its corresponding Il is like this:

. Class public abstract auto ANSI beforefieldinit cabstract
Extends [mscorlib] system. Object
{
} // End of class cabstract

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.