Foreword

C # and Java are basically similar in their use of classes, abstract classes, and interfaces, except that the corresponding keywords are different. In this section, we just compare the three concepts in C # and Java when they are used specifically to see what is different. The place.

Class inheritance

C # and Java are consistent in the way they define classes. There isn’t much to explain here. We go directly to class inheritance. In Java, inheritance is achieved through the extends keyword, while in C # it is a colon (: ) To inherit, very elegant and concise, Java is as follows:

class   Animal {}

class   Tiger extends   Animal {}

In C #:

class Animal {}

class Tiger: Animal {}

Now that we have explained inheritance, it must also involve method rewriting. Regardless of Java or C #, the concept of rewriting is the same: method rewriting means defining a method in a subclass, which is already defined in the parent class. Identical method signatures-same name, parameters, and return type. The rewrite in Java is as follows:

 

 

class Animal {
     void Run () {
        System.out.println ( "Animals may run" );
    }
}

class Tiger extends Animal {
     void Run () {
        System.out.println ( this .getClass (). GetSimpleName () + "will run" );
    }
}

 

 

Tiger tiger = new Tiger ();
 tiger.Run ();

In C # we can also do the above code, but there will be warnings, as follows:

 

 

    class Animal
    {
        public  void Run ()
        {
            Console.WriteLine ( " Animal may run " );
        }
    }
    class Tiger: Animal
    {
        public  void Run ()
        {
            Console.WriteLine ($ " {GetType (). Name} will run " );
        }
    }

 

 

After we have written the above, we will find that the compiler prompts the following warning, why? It is not difficult to imagine, because our child class inherits the parent class, which is equivalent to the method of the parent class in the child class (we are equivalent here, because if there are two identical methods in a class That is, the method name and signature are the same, it must be wrong, and the concept of overloading and rewriting must be distinguished), so a warning prompt will be issued.

 

In fact, the rewrite in C # is as follows. If the parent method is likely to be overwritten in the future according to the business, it is modified by the virtual keyword. When the method in the parent class is overridden, the override key is used. Word modification

 

 

    class Animal
    {
        public  virtual  void Run ()
        {
            Console.WriteLine ( " Animal may run " );
        }
    }
    class Tiger: Animal
    {
        public  override  void Run ()
        {
            Console.WriteLine ($ " {GetType (). Name} will run " );
        }
    }

 

 

interface

There is basically no difference in the use of abstract classes in C # and Java. Both are definable and non-abstract methods. Abstract methods can only be used in abstract classes and interfaces. Some people have said why they cannot be defined in classes. It involves learning methods, because they are all object-oriented languages, so we have to think and give examples in the way of human thinking (don’t feel like a new concept every time you learn a language, many of them are connected), because After the class is instantiated, it is a concrete object. Since it is a concrete object, the variables and methods in the object must be fully implemented. So we must realize it suddenly and openly. The only small difference in the definition of an abstract method in an interface is that the idea compiler will prompt that abstract is completely unnecessary, because the interface is an abstract type, and it will not be prompted in vs compilation. So what is the definition of an interface in Java? An interface is an abstract type that contains a collection of methods and constant variables. It is one of the core concepts in Java and is used to implement abstraction, polymorphism, and multiple inheritance . Next we define an electronic product interface as follows:

 

 

interface Electronic {

    // Constant 
    String LED = "LED" ;

    // abstract method 
    int getElectricityUse ();

    // static method 
    static  boolean isEnergyEfficient (String electronicType) {
         if (electronicType.equals (LED)) {
             return  true ;
        }
        return  false ;
    }
    
    // default method 
    default  void printDescription () {
        System.out.println ( "Electronic Description" );
    }
}

 

 

Next, let’s implement the above interface through specific electronic products, and implement the interface through the implements keyword.

 

 

class Computer implements Electronic {
    
    public  int getElectricityUse () {
         return 1000 ;
    }
}

 

 

Next we make the following calls:

 System.out.println (Computer.LED);
 Computer computer = new Computer ();
 System.out.println (computer.getElectricityUse ());

So the question comes, when defining an interface, what can we define in the interface? Constant variables, abstract methods, static methods, default methods . For static methods and default methods are new features that only appeared in Java8, constant variables must be decorated with public, static, final. It is easy to understand that we come to access static methods that appear through new classes through the class. What is the situation?

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_1.png

The new Java 8 feature adds static methods to the interface. Since it is a static method, we can’t access the static method through the implementation of the interface, but the class still has a meaning? Is there a pit in my head? Is it beginning to doubt life? Don’t panic, we must learn to analyze the problem: because a class can implement multiple interfaces, if a class implements multiple interfaces and the same static method is defined in multiple interfaces, the class will inherit the same Static methods. At this point, the compiler does not know which interface to call the static method in . Therefore, it appears that we have implemented an interface but cannot access the static methods in the interface. This is the limitation of Java 8 for defining static methods in the interface, that is , the static methods in the interface cannot be inherited by the class that implements it. The interface accesses static methods . as follows:

 System.out.println (Electronic.isEnergyEfficient ("LED"));

Then the problem comes again. If we also define the static methods in the interface in the class that implements the interface as follows, will there be a rewrite situation (in order to observe whether to rewrite, the judgment condition is negated)?

 

 

class Computer implements Electronic {

    public  int getElectricityUse () {
         return 1000 ;
    }

    static  boolean isEnergyEfficient (String electronicType) {
         if (! electronicType.equals (LED)) {
             return  true ;
        }
        return  false ;
    }
}

 

 

System.out.println (Computer.isEnergyEfficient ("LED" ));
System.out.println (Electronic.isEnergyEfficient ("LED"));

From the above we know that the implementation class of its interface has a static method with the same name, and none of it will be overridden. So what’s the point of defining a static method in an interface? In my opinion: static methods belong to the class level. In java8, static methods are extended to interfaces, which is equivalent to using interfaces as classes. Then the problem comes again. There are static methods and default methods in the new features of java8. What is the difference between static methods and default methods? We add a method with the same name as the default method in the interface implementation class, as follows:

 

 

class Computer implements Electronic {

    public  int getElectricityUse () {
         return 1000 ;
    }

    static  boolean isEnergyEfficient (String electronicType) {
         if (! electronicType.equals (LED)) {
             return  true ;
        }
        return  false ;
    }

    public  void printDescription () {
        System.out.println ( "Computer Electronic" );
    }
}

 

 

Next we call the above method through the class instance and anonymous class as follows:

 

 

        // Instance class 
        Electronic computer = new Computer ();
        computer.printDescription ();

        // Anonymous class 
        Electronic e = new Electronic () {
            @Override
            public  int getElectricityUse () {
                 return 50 ;
            }

            @Override
            public  void printDescription () {
                System.out.println ( "Anonymous Electronic Description" );
            }
        };
        e.printDescription ();

 

 

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_2.png

We see that both class instances and anonymous classes can override the default methods. From the above we can conclude that static methods on interfaces can only be called by defined interfaces, and default methods on interfaces can be overridden by interface implementation class instances or anonymous interfaces Written, further elaborates that interfaces are extended to be used as classes in java8. The default method of the interface is to provide common functions, one to extend the interface, and the other does not need to destroy the interface implementation class. Interface static methods are used to provide public helper methods without the need to create additional classes. We can define attributes in the C # interface, but not in Java. At the same time, we can also define default methods for interfaces in C # 8.0. At the same time, there are no restrictions on the default methods. Static methods, this is incomparable to Java, such as the following:

 

 

    public  interface Electronic
    {
        string Color { get ; set ;}

        bool isEnergyEfficient ( string electronicType)
        {
            return  true ;
        }
    }

 

 

Abstract classes and interfaces

Both the abstract class and interface are used to abstract classes in the Java language (the abstract class in this article is not translated from the abstract class, it represents an abstract body, and the abstract class is used to define abstract classes in the Java language One method, please pay attention to the reader’s distinction), so what is an abstract class, and what benefits can we get from using an abstract class? “Reprinted:
https://www.ibm.com/developerworks/cn/java/l-javainterface-abstract/index.html

In object-oriented concepts, we know that all objects are represented by classes, but not the other way around. Not all classes are used to describe objects. If a class does not contain enough information to describe a specific object, such a class is an abstract class. Abstract classes are often used to characterize the abstract concepts we derive from analyzing and designing problem domains. They are abstractions of a series of concrete concepts that look different but are essentially the same. For example, if we develop a graphic editing software, we will find that there are some specific concepts such as circles and triangles in the problem domain. They are different, but they all belong to the concept of shape. Existence is an abstract concept. It is precisely because the abstract concept does not have a specific concept in the problem domain, so the abstract class used to represent the abstract concept cannot be instantiated.

In the object-oriented field, abstract classes are mainly used for type hiding. We can construct an abstract description of a fixed set of behaviors, but this set of behaviors can have any number of possible specific implementations. This abstract description is an abstract class, and any set of possible concrete implementations is represented by all possible derived classes. A module can operate on an abstract body. Because the module depends on a fixed abstract body, it can not be modified; at the same time, by deriving from this abstract body, the behavioral function of this module can also be extended. Readers familiar with OCP must know that in order to implement one of the core OCP (Open-Closed Principle) principles of object-oriented design, abstract classes are the key.

Look at abstract class and interface from the grammar definition level

At the grammatical level, the Java language provides different definitions for the abstract class and interface. The following uses the definition of an abstract class named Demo as an example to illustrate this difference.

The way to use the abstract class to define the Demo abstract class is as follows:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_3.png

 

The way to use the interface to define the Demo abstract class is as follows:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_4.png

 

 

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

 

Seeing abstract classes and interfaces from a programming perspective

From a programming perspective, both abstract classes and interfaces can be used to implement the “design by contract” idea. However, there are some differences in the specific use. First, the abstract class represents an inheritance relationship in the Java language. A class can only use the inheritance relationship once. However, a class can implement multiple interfaces. Perhaps this is a compromise that the designers of the Java language have made in considering Java’s support for multiple inheritance. Second, in the definition of the abstract class, we can give the method the default behavior. However, in the definition of interface, methods cannot have default behavior. In order to bypass this restriction, delegation must be used, but this will add some complexity and sometimes cause great trouble.

There is another serious problem that the default behavior cannot be defined in the abstract class, that is, it may cause maintenance trouble. Because if you later want to modify the interface of the class (usually represented by abstract class or interface) to adapt to the new situation (for example, adding a new method or adding new parameters to the used method), it will be very troublesome, It can take a lot of time (especially for many derived classes). But if the interface is implemented through the abstract class, then you may only need to modify the default behavior defined in the abstract class. Similarly, if the default behavior cannot be defined in the abstract class, the same method implementation will appear in every derived class of the abstract class, which violates the “one rule, one place” principle, causing code duplication, which is also not good for the future Maintenance. Therefore, be very careful when choosing between abstract classes and interfaces.

 

Looking at abstract class and interface from the design concept level

The differences between the abstract class and the interface are mainly discussed from the perspective of syntax definition and programming. The differences at these levels are relatively low-level and non-essential. This section will analyze the differences between the abstract class and the design concept reflected by the interface. The author believes that the analysis of this level can understand the essence of the two concepts.

As mentioned earlier, the abstarct class embodies an inheritance relationship in the Java language. To make the inheritance relationship reasonable, there must be an “is a” relationship between the parent class and the derived class, that is, the parent class and the derived class are conceptual in nature. It should be the same (Reference [3] has a long and in-depth discussion on the “is a” relationship, and interested readers can refer to it). This is not the case for interfaces. It does not require that the implementor of the interface and the definition of the interface be essentially the same in terms of the concept, but merely implement the contract defined by the interface. In order to make the discussion easier to understand, a simple example will be used for illustration.

Consider such an example. Suppose there is an abstract concept about Door in our problem domain. The Door has two actions, open and close. At this time, we can define a type representing the abstract concept through the abstract class or interface. The definitions are as follows:

Use Abstract class to define Door:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_5.png

 

Use Door to define Door:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_6.png

 

Other specific types of Doors can be defined by extending the Door defined by the abstract class or implementing the Door defined by the interface. It seems as if there is no big difference between using an abstract class and an interface.

If Door is required now, it also needs to have alarm function. How do we design the class structure for this example (in this example, it is mainly to show the difference between the abstract class and the interface reflected in the design concept, and other unrelated issues have been simplified or ignored)? The possible solutions are listed below, and these different solutions are analyzed from the design concept level.

Solution one:

Simply add an alarm method to the definition of Door, as follows:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_7.png

 

Then the definition method of AlarmDoor with alarm function is as follows:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_8.png

 

This method violates a core principle ISP (Interface Segregation Priciple) in object-oriented design. In the definition of Door, the inherent behavior method of Door concept is mixed with the behavior method of another concept “alarm”. One problem caused by this is that modules that only rely on the concept of Door will change due to the change of the concept of “alarm” (such as modifying the parameters of the alarm method), and vice versa.

 

Solution two:

Since open, close, and alarm belong to two different concepts, they should be defined in the abstract classes representing these two concepts according to the ISP principles. The definition methods are: both concepts are defined using the abstract class method; both concepts are defined using the interface method; one concept is defined using the abstract class method, and the other concept is defined using the interface method.

Obviously, because the Java language does not support multiple inheritance, it is not feasible to define both concepts using the abstract class method. The latter two methods are feasible, but their choice reflects the understanding of the nature of the concepts in the problem domain 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, then two problems are reflected: 1. We may not understand the problem area clearly. Is AlarmDoor essentially a door or an alarm? 2. If there is no problem in our understanding of the problem domain, for example: through analysis of the problem domain, we find that AlarmDoor is essentially the same as Door in concept, then we have not been able to correctly reveal our design intent when implementing, because The definition of these two concepts (both are defined using the interface method) does not reflect the above meaning.

If our understanding of the problem domain is: AlarmDoor is Door in essence, and it also has the function of alarm. How can we design and implement to clearly reflect what we mean? As mentioned earlier, the abstract class represents an inheritance relationship in the Java language, and inheritance relationships are essentially “is a” relationships. So for the concept of Door, we should use the abstarct class to define it. In addition, AlarmDoor also has an alarm function, indicating that it can complete the behavior defined in the alarm concept, so the alarm concept can be defined through the interface. As follows:

Java_entry_series_[5]_inheritance,_abstract_classes,_interfaces_9.png

 

This way of implementation basically can clearly reflect our understanding of the problem domain and correctly reveal our design intent. In fact, the abstract class represents the “is a” relationship, and the interface represents the “like a” relationship. You can use it as a basis when choosing. Of course, this is based on the understanding of the problem domain. For example, if we think AlarmDoor In essence, it is an alarm, and at the same time has the function of Door, then the above definition method will be reversed. Abstract class and interface are two ways to define abstract classes in the Java language, and they have great similarities. However, their choice often reflects the understanding of the nature of the concepts in the problem domain, and whether the reflection of the design intent is correct and reasonable, because they represent different relationships between the concepts (although they can achieve the required function). This is actually a common usage of language.

Summary

In this section, we explain class inheritance, abstract classes, interfaces, and new features that appeared in java8 in detail. At the same time, I have reproduced a long-term article but the idea has not changed. Personally, I think a very good article about abstract classes and interfaces The difference is that I hope to bring deeper thinking to beginners like me.

Java entry series [1] string creation method

Java entry series [2] string features

Java entry series [3] stringbuilder string buffer

Java entry series [4] packaging class

Java entry series [5] inheritance abstract classes interfaceson

Java entry series [6] Principles of dynamic array

Java entry series [7] collection arraylist

Java entry series [8] principles of doubley linked list alogrithm

Java entry series [9] linkedlist source code analysis

Java entry series [10] Hash algorithm principle

Java entry series [11] Hashtable source code analysis

Java entry series [12] Hashcode and equals

Java entry series [13] Principles of the read-black tree algorithmn method

Java entry series [14] Hashmap source code ananlysis

 

Orignal link:https://www.cnblogs.com/CreateMyself/p/11437029.html