Interview: what are the similarities and differences between abstract classes and interfaces?

Posted by ElectricShaka on Wed, 16 Feb 2022 07:43:26 +0100

  • In java, beginners usually don't understand interfaces and abstract classes, which is also an easy question to ask in an interview. Now let me talk about my understanding. If there is anything wrong, I hope you can criticize and correct it. Thank you very much.
  • 1. How to define and inherit abstract classes?
  • 2. How to define and implement interfaces?
  • 3. Summary and comparison

1. How to define and inherit abstract classes?

We define an abstract class person Class means class (person):

//Use keyword abstract
public abstract class person {
    //The abstract method of eating has been realized
    public void eat(){
        System.out.println("I eat in an abstract way");
    }
    
    //Empty implementation method of public modification
    public void run(){}
    
    //No modification, empty implementation
    void walk(){}
    
    //protected modified method, empty implementation
    protected void sleep(){}
    
    //Empty implementation method of private modification
    private void read(){}
}

  • 1. Abstract classes are decorated with abstract. They can have abstract methods, or they can have no abstract methods at all, or they can be implemented methods. However, all methods must be implemented. Empty implementation (public void walk() {}) is also a kind of implementation, and public void eat() cannot be written, which must be followed by braces.
  • 2. The method modifier can make public,protected,private, or none. No default is that it can only inherit under the same package. If it is private, the subclass cannot inherit this method when inheriting, and there is no way to modify it
  • Now let's write a teacher Class inherits abstract classes

Inherit under the same package:

Different packages inherit from the following:

The correct code under the same package is as follows (do not rewrite private methods):

public class teacher extends person {
    @Override
    public void run(){
        System.out.println("I'm an entity class method");
    }
    @Override
    void walk(){
        System.out.println("I'm an entity class method");
    }
    @Override
    protected void sleep(){
        System.out.println("I'm an entity class method");
    }
}

  • The results are as follows (there is no method to override the abstract class to eat, so the default method of the abstract class will be called):
  • The following code is the code that rewrites the eat() method. The rewriting works even if @ Override is not used:
public class teacher extends person {
    public void eat(){
        System.out.println("I'm an entity class method to eat");
    }
    @Override
    public void run(){
        System.out.println("I'm an entity class method");
    }
    @Override
    void walk(){
        System.out.println("I'm an entity class method");
    }
    @Override
    protected void sleep(){
        System.out.println("I'm an entity class method");
    }
}
  • As a result, the method of eating was covered:
  • Abstract classes cannot be instantiated, for example:
  • Subclasses can implement the methods of the abstract class, or not, or only a part of them. In this way, there is no problem in running. If they are not implemented, the call uses the empty implementation of the abstract class by default, that is, nothing is output. If the abstract class has an implementation, the default method of the abstract class will be output. For example:
  • Abstract classes can have concrete methods and properties (member variables)
  • There are many similarities between abstract classes and ordinary classes, such as static members and static code blocks.

2. How to define and implement interfaces?

  • An interface is an abstraction of a method or action, such as person If you want to be a teacher, you can implement the teacher interface, which can be understood as increasing ability.
  • The interface does not allow defining uninitialized attribute variables. You can define public static final int i=5;, And public int number =0;, But public int num is not allowed; Defined in this way, all private variables are not allowed. The following is the picture

Define public int number =0; The default is final, so its value cannot be changed:

Here is the correct interface code: teacher java

public interface Teacher {
    public static final int i=5;
    public int number =0;
    public void teach();
    void study();
}
  • Implementation class: teacherclass java
public class TeacherClass implements Teacher{
    @Override
    public void teach() {
        System.out.println("I'm a teacher. I want to teach");
        System.out.println("Interfaced static int Yes:"+i);
    }

    @Override
    public void study() {
        System.out.println("I am a teacher, I also want to study");
        System.out.println("Interfaced int number Yes:"+number);
    }
}
  • Test class test java
public class Test {
    public static void main(String[] args){
        TeacherClass teacherClass = new TeacherClass();
        teacherClass.study();
        teacherClass.teach();
        System.out.println("-----------------------------------------------------");
        Teacher teacher =teacherClass;
        teacher.study();
        teacher.teach();
    }
}

result:

Analysis: the member variables defined in the interface are final and immutable. To implement the interface, you must implement all the methods in the interface, not only a part. If static final is not used, it is also final by default. At the same time, you must have initialization values. The interface cannot directly create objects, such as teacher, teacher = new teacher(), However, you can first create an implementation class of the interface, and then assign a value to the interface object.

3. Summary and comparison

abstract class

Interface

Use the keyword abstract to decorate

Use keyword interface

Using the keyword extends to implement inheritance, you can only implement part of the methods, part of them not, or not

implements to implement the interface. To implement the interface, you must implement the methods in it

The method in the abstract class can be empty and can be implemented by default, but it must be with {}

The methods in the interface have no implementation body, that is {}

Abstract classes can have specific methods and attributes, static code blocks, static member variables

There can be no ordinary member variables in the interface. They must be immutable final member variables, and all member variables must be public

Methods in abstract classes can be public, protect or private, but private cannot inherit, so few people will write this. If there is no modifier, only classes under the same package can inherit

The methods of the interface can only be public or have no modifiers. All private modifiers will report errors

If there are changes and new methods are added, the default method can be implemented directly in the abstract class or in the implementation class

New methods added to the interface must be declared in the interface and then implemented in the implementation class

Abstract classes cannot create objects directly

The interface can not directly create objects, but can be assigned to the objects of the implementation class

Abstract classes can have main methods, and we can run them directly. Abstract classes can also have constructors

An interface cannot have a main method or a constructor

So when do we use interfaces and abstract classes?

  • java has a disadvantage that it can only realize single inheritance. Personally, I think the interface is designed to make up for single inheritance.
  • An interface is an abstraction of the essence. For example, a person can be designed as a person Class, an abstract class, provides related methods and properties, but the interface only provides methods, that is, it is the abstraction of methods like adding functions.
  • If the default implementation is required or the basic functions are constantly changing, it is recommended to use the abstract class. If only one method is added, it is recommended to use the interface. If you want to realize multiple inheritance, you can only use the interface together with the abstract class to achieve the desired functions.

This article is a record of the beginning of learning. It is only a primary comparison. You need to Keep going for in-depth study~

This article only represents your own learning accumulation records or learning notes. If there is infringement, please contact the author to delete it. No one is perfect, so is the article. Your writing is immature. Don't spray if you don't have talent. If there are mistakes, please point them out. Thank you very much~

The road of technology is not for a while. The mountains are high and the rivers are long. Even if it is slow, it will not stop. Keep going~