I’m sure you all get the feeling that there are too many similarities and too many differences between abstract classes and interfaces. Often these two things can confuse beginners, whether in the actual programming, or in the interview, abstract classes and interfaces are very important! Hopefully by the end of this blog post you will be comfortable with both…

@[toc]

Abstract classes as I understand them

1, 1 Abstract class and class like flavor

Abstract classes, like classes, can inherit from each other. Abstract classes, like classes, can inherit from each other.

Abstract Class As the name defines, it is also a class

1, 2 Abstract methods

Abstract methods must not have a body. Abstract methods must use the abstract keyword. Abstract methods must be abstract classes

Abstract classes do not necessarily have abstract methods

1, 3 Abstract classes and classes of strange flavor

1. Abstract classes must be modified with the abstract keyword. Abstract classes have a constructor that cannot be used to create a final instance of an object. The constructor cannot be used to create a final instance of an object. The code for this sentence is as follows:

// Define an abstract class A
abstract class A{
   // Define an internal abstract class B
    static abstract class B{  // Static defines an inner class as an outer class
        public abstract voidsaoMethod(); }}class C extends A.B{

    public void saoMethod(){
        System.out.println("======saoMethod method executes ======");
    }
}
public class StaticDemo {

    public static void main(String[] args) {
        A.B ab = new C();// Upward transitionab.saoMethod(); }} Result: ======saoMethod executes ======Copy the code

“C extends A.B” means “C extends A.B”. Yes, when an inner abstract class declared static is equivalent to an outer abstract class, use “outer class” when inheriting. The form “inner class” represents the class name. This SAO operation is true in the stable belt skin.

Abstract class is a special class, abstract class and ordinary class have essential difference

1, 4 Master abstract classes

Abstract classes exist for inheritance. Defining an abstract class, but not inheriting it, creates an abstract class that is meaningless!

Abstract classes have constructors but cannot be instantiated directly. Creating an object involves an upward transition, primarily to be called by its subclasses

And the fact that there can be no abstract methods for abstract classes is just an important concept to keep in mind. In practice, abstract classes usually have abstract methods, otherwise the abstract class has no meaning, and ordinary classes are no different!

If A common class A inherits an abstract class B, subclass A must implement all the abstract methods of its parent class B. If subclass A does not implement the abstract methods of parent class B, then subclass A must also be defined as an abstract class, that is, an abstract class.

2. Interface as I understand it

An interface is a special case of an abstract class. There are too many similarities and too many differences between the two. Interfaces, by contrast, are more like an abstraction of behavior!

2. 1 Interface features

1. The default method type is public abstract, and the default variable type is public static final. 3, the interface can achieve “multiple inheritance”, a class can implement multiple interfaces, the implementation of the format is directly separated by a comma.

2, 2 interface must be known

The interface can contain only public static final variables. The default value is public static final. Using private variables will fail compilation.

All methods in the interface are implicitly specified as public abstract methods and only public abstract methods. Using other keywords such as private, protected, static, and final will fail compilation.

2, 3 Interface error

There are a lot of articles on the Internet saying that all the methods in the interface are abstract methods. The blogger went back and found that this is actually not rigorous enough. Let’s just look at a simple program

package InterfaceDemo;

interface AA{   AA / / interface
   default void hh(){
       System.out.println("123");
   };
}

class BB implements AA{  // Implement the interface
    
}

public class InterfaceDesign {

    public static void main(String[] args) {
        AA a=new BB(); // Create an instance by implementing the classa.hh(); }} Run result:123
Copy the code

Obviously hh method is not abstract method, but this design will lose the meaning of the interface, the actual development of such code will not appear, it is really a bit of special flavor, so I do not deny the online speech, but feel not rigorous enough, I think we still pay attention to better… If an interviewer hears you say something like this, he or she may be impressed by you and think that you are a learner who is eager to learn, to explore and to think independently

3. Essential differences between abstract classes and interfaces

The essential differences between abstract classes and interfaces mainly come from syntax differences and design ideas

3, 1

1. An abstract class can have constructors, but an interface cannot.

2. An abstract class can have member variables of any type, and an interface can only have public static final variables

3. Abstract class can contain non-abstract common methods, interface can have non-abstract methods, such as deaflut method

4. The access types of abstract methods in an abstract class can be public, protected, or (default, although eclipse does not error, but should not). However, abstract methods in an interface can only be of public type, and the default is public Abstract.

5. An abstract class can contain static methods, but an interface cannot

6. Both abstract classes and interfaces can contain static member variables. The access type of static member variables in an abstract class can be any, but the variables defined in the interface can only be public static final, which is the default type.

7. A class can implement multiple interfaces, but can inherit only one abstract class.

3, 2 design ideas

For an abstract class, if you need to add a new method, you can directly add a concrete implementation in the abstract class (equivalent to writing a common method of the common class and adding the implementation code of the method body), and the subclass can not change; This is not the case with interfaces. If an interface changes, all classes that implement that interface must change accordingly. This should make sense.

From the design point of view, abstract class is a kind of class abstraction. Abstract class is to abstract the whole class, including properties, behavior. While an interface is an abstraction of behavior, an interface is an abstraction of class parts (behavior). In a way, interfaces are more like abstract abstractions!

What to make of the above paragraph?

Understand the difference between the two design ideas from the programmer yichun and flower girl (a head of lovely little sows) the story begins, programmers yichun every day living in three point one line, not to eat is sleeping, leisure will knock on the code, and the flower girl much, every day is one point one line of life, not to eat is sleeping, leisure is not eat is sleeping. Programmers yichun and flower girl all live a happy and comfortable life, suddenly one day, swell, shot stools ~ ~ it’s big day, the evil of the product manager to demand, to design a programmer yichun and flower girl’s a program that requires the use of an abstract class or interface design, how to design, will you be this time two design scheme is given below…

Scheme 1: Abstract class design is used to design eat, sleep and qiaoDaiMa methods respectively. The specific codes are as follows:

abstract class Myclass{
    public abstract void eat();
    public abstract void sleep();
    public abstract void qiaoDaiMa();
  }
Copy the code

Scheme 2: Use interface design to design eat, sleep and qiaoDaiMa methods respectively. The specific codes are as follows:

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
    public abstract void qiaoDaiMa();
  }
Copy the code

Obviously, no matter which class inherits the abstract class or implements the interface above, the same situation will occur: overriding their abstract methods. If there are a hundred programmers yichun, the above design is well solved. But when it comes to flower girl, it doesn’t work, because flower girl doesn’t code this kind of high-end operation! A hundred flower girls rewrite qiaoDaiMa method does not make sense ah, obviously there is a problem with this design.

It can be seen from the above that eat and sleep are not behaviors (methods) in the same category for qiaoDaiMa method. In fact, we can define an abstract class containing eat and sleep methods, and define an interface containing qiaoDaiMa methods.

abstract class Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

interface MyclassTwo{
    public abstract void qiaoDaiMa();
  }
  
class YiChun extends Myclass implements MyclassTwo{

          @Override
          public void eat() {
              
          }

          @Override
          public void sleep() {

          }

          @Override
          public void qiaoDaiMa() {

          }
      }
Copy the code

We just need to let a hundred programmers yichun inherit abstract classes and implement interfaces, and Hua Girl inherit abstract classes directly. Such a design is perfect…

Again, it’s irresponsible to talk like this. Why pinch? As you can see, there seems to be no difference between an abstract class and an interface. If the abstract class is replaced by an interface, the implementation effect is the same.

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

abstract class MyclassTwo{
    public abstract void qiaoDaiMa();
  }
Copy the code

So, in order to explain the distinction between clear design ideas, the story of programmer Yichun and flower girl has to go on…

As we all know, cute sows are usually pink, right? At this time our product manager changed the demand again. What? One of the 100 pigs in the product manager’s family is a black and white SAI, eh…

The evil product manager will only change the requirements unreasonable, but the product manager will never know that he blindly forced programmers, programmers do not know how good they are!

As we all know, cute sows are usually pink, right? At this time our product manager changed the demand again. What? One of the 100 pigs in the product manager’s family is a black and white SAI, eh…

The evil product manager will only change the requirements unreasonable, but the product manager will never know that he blindly forced programmers, programmers do not know how good they are!

Abstract classes and interfaces can have member variables, but interfaces can only be public static final because of this. This is where the essence of abstract class and interface design comes in.

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

abstract class MyclassTwo{
    String color="red";
    public abstract void qiaoDaiMa();
  }
Copy the code

Let yichun class so designed

package AbstractTest;

interface Myclass {
    public abstract void eat();

    public abstract void sleep();
}

abstract class MyclassTwo {
    String color = "red";

    public abstract void qiaoDaiMa();
}

class YiChun extends MyclassTwo implements Myclass {

    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }

    @Override
    public void qiaoDaiMa() {

    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        YiChun yc = newYiChun(); }}Copy the code

However, Yichun for color this attribute can be ignored, can be as does not exist, unless Yichun does not dislike himself is also a red sai Page ha ha ha….

And flower girl class should pay attention to! Then let 100 pigs in the product manager’s house design code as follows;

package AbstractTest;

interface Myclass {
     public abstract void qiaoDaiMa();
}

abstract class MyclassTwo {
    String color = "red";

    public abstract void eat();
    public abstract void sleep();
  
}

class Pig extends MyclassTwo {

    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }

}

public class AbstractDemo {
    public static void main(String[] args) {
        Pig p = new Pig ();
        String color = "blackWhite"; System.out.println(color); }}Copy the code

String color = “blackWhite”; The color attribute is red by default…

At this time, the abstract class and interface can not be replaced, so that the abstract class and interface design idea is very clear, what do you know

If this article helped you at all, please give it a thumbs up. Thanks

Finally, if there is insufficient or improper place, welcome to criticize, grateful!

Welcome to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology