JAVA notes object-oriented -- inherit interfaces and abstract classes

Posted by grooveman on Wed, 02 Feb 2022 04:15:23 +0100

Introduction: in the previous chapter, we studied inheritance in java in detail. Inheritance in java is single inheritance, which will lead to a problem. If a class wants to call the relevant contents of the other two classes at the same time, it cannot be realized as single inheritance, what should we do? java provides another way - interface to solve this problem.

1, Abstract method:

In the process of inheritance, the subclass overrides the method with the same name of the parent class. We find a problem. The method body of the parent class method has no meaning, so can it be omitted? The answer is yes and can be omitted. The method that omits the method body is an abstract method.

1. Definition:

Abstract method is a special method: this method is modified by abstract. It has only declaration but no concrete implementation. The declaration format of the abstract method is:

Permission modifier return value type method name(parameter list);   //No method body

In the previous chapter, our parent class Animal defines a printing method. The specific implementation of printing is unknown. The code is as follows:

public abstract void print();   //Abstract method, no method body implementation

Summary:

  • Methods modified by abstract and without method body are called abstract methods;
  • Abstract methods must exist in abstract classes, not in non abstract classes;
  • Abstract methods must be implemented in their subclasses, unless the subclasses are also abstract classes;

2, Abstract class:

1. Definition:

A class modified by abstract is called an abstract class. If a class contains abstract methods, it must be an abstract class. On the contrary, if a class is an abstract class, it does not necessarily contain abstract methods.

abstract  Class name{...}

If Animal is defined as an abstract class:

abstract Animal{
	//Omitting properties and methods
}

2. Function of abstract class:

Abstract classes exist for inheritance. If you define an abstract class but don't inherit it, you create it for nothing, because you can't do anything with it. For a parent class, if a method implemented in the parent class has no meaning and must be implemented differently according to the actual needs of the child class, the method can be declared as an abstract method, and the class will become an abstract class at this time.

Classes containing abstract methods are called abstract classes, but it does not mean that there can only be abstract methods in abstract classes. Like ordinary classes, they can also have member variables and ordinary member methods. The difference between abstract classes and ordinary classes is as follows:

  • The abstract method must be public or protected (because if it is private, it cannot be inherited by subclasses, and subclasses cannot implement the method). By default, it is public.
  • Abstract classes cannot be used to create objects;
  • If a class inherits from an abstract class, the subclass must implement the abstract methods of the parent class. If the subclass does not implement the abstract method of the parent class, the subclass must also be defined as an abstract class.

In other aspects, abstract classes are no different from ordinary classes. General abstract classes are used to improve extensibility in inheritance.

3. Specific use of abstract classes:

Similarly, taking the Animal case in the previous chapter as an example, the print method of the parent class Animal needs to be implemented through specific subclasses, so it has no meaning in the parent class, so we can define the method as an abstract method. If there is an abstract method in a class, the class must be an abstract class, and the code is as follows:

Abstract parent class:

package cn.hz;

/**
 * @author hz
 * @version 1.0
 *
 * Parent class: animal class -- abstract class
 */
public abstract class Animal { ;
    private String name;    //Attribute: nickname
    private Integer health; //Attributes: health values
    private Integer love;   //Attribute: Intimacy

    //Omit the corresponding set/get method and construction method

    //Define abstract method - Print
    public abstract void print();

}

Non Abstract subclass:

package cn.hz;

/**
 * @author hz
 * @version 1.0
 *
 * Subclass: dog's class -- non Abstract subclass
 */
public class Dog extends  Animal{
    private String strain;  //Attribute: new attribute added to subclass
    
    public String getStrain() {
        return strain;
    }

    public void setStrain(String strain) {
        this.strain = strain;
    }

    //Subclass overrides parent class abstract method
    @Override
    public void print() {
        System.out.println("Information about dogs"+getName()+"..."+getStrain());
    }
}

Through the analysis of the above examples, the abstract parent class defines the abstract method, and the non Abstract subclass implements the abstract method, which can not only achieve the standardization of the code, but also realize the scalability of the code.

Summary:

  • If a class contains abstract methods, the class must be abstract and must be modified by abstract;
  • If a class is abstract, it can contain abstract and non abstract methods
  • If a class is abstract, it cannot be instantiated, but must be instantiated through its non Abstract subclass

3, Interface:

Inheritance in java is single inheritance. In order to improve scalability, java provides a mechanism interface. What is an interface?

1. Definition of interface:

Interface is called interface in English. In software engineering, interface generally refers to methods or functions called by others. From here, we can understand the original intention of the Java language designer, which is the abstraction of behavior.

An interface represents a capability and a specification

interface Interface name{...}

If a CRUD interface for data operation is defined, the code is as follows:

interface CRUD{
	//Omit properties and methods
}

Interfaces can contain variables and methods. However, it should be noted that the variables in the interface will be implicitly specified as public static final variables (and can only be public static final variables. Using private modification will report compilation errors), The method will be implicitly specified as a public abstract method and can only be a public abstract method (using other keywords, such as private, protected, static, final and other modifiers will report compilation errors), and all methods in the interface cannot have specific implementations, that is, the methods in the interface must be abstract methods. From here, we can vaguely see the difference between interface and abstract class. Interface is an extremely abstract type. It is more "abstract" than abstract class, and generally, variables are not defined in the interface.

2. Implementation of interface:

After the interface is defined, it needs to be implemented through the implementation class. The syntax is as follows:

Implementation class  implements Interface{
	//Implementation of abstract methods of all interfaces
}

As the interface CRUD of database operation defined above, the code of implementation class CRUDDao is as follows:

public class CRUDDao implements CRUD {
    //Implementation of all abstract methods in CURD
}

The method in the implementation class must be a non abstract method.

3. Characteristics of interface:

Class inheritance in java is single inheritance, and interfaces in java are multi inheritance and multi implementation.

For example, now we define two parent interfaces and one parent class:

//Parent interface A
public interface A {
    //Omit content
}
//Parent interface B
public interface B {
    //Content omission
}

//Parent class
public class AA{
	//Content omission
}

**Interface multi inheritance: * * define that interface C can inherit from interfaces a and B at the same time

//Sub interface
public interface C extends A,B {
    //Content omission
}

**Multi class implementation: * * define the implementation class Demo1, which can implement a and B interfaces at the same time

public class Demo implements A,B{
	//Content omission
}

Whether it is multiple implementations of classes or multiple inheritance of interfaces, be sure to use "," to separate multiple interfaces.

Single inheritance of classes and multiple implementations of interfaces: define the implementation class Demo2 to inherit the parent class AA and implement interfaces a and B

public class Demo2  extends AA  implements A,B {
    //Omit content
}

be careful:

  • If a class inherits a class and implements an interface, the inheritance must be in front and the order cannot be exchanged.
  • If an implementation class inherits an abstract class and implements an interface, the implementation class must implement all abstract methods in the abstract class and interface.
  • Class implementation can be multiple, but class inheritance must be single inheritance, and interface inheritance can be multiple inheritance

4. Specific use of interface:

Through the above study, you may have a deep understanding of the corresponding interface, so how to use the interface? Next, let's explain it in detail through an example.

**Requirements: * * realize the function of anti-theft door through writing, and can be extended in the future.

**Analysis: * * the door has the functions of "opening" and "closing", and the lock has the functions of "locking" and "unlocking". The anti-theft door contains both common functions. The door and anti-theft door are defined as abstract classes, and the anti-theft door can inherit the door and lock, but the inheritance of java class is single inheritance and cannot support multiple inheritance. What if the above functions are realized?

  • Define the door as an abstract class and the lock as an interface
  • The anti-theft door inherits the door and realizes the interface of lock

Class diagram:

Code implementation:

package cn.hz;

/**
 * Class defining door -- abstract class
 * @author hz
 * @version 1.0
 */
public abstract class Door {
    private String type;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }

    /**
     * Define the method of closing the door
     */
    public abstract void close();

    /**
     * Define the method of opening the door
     */
    public abstract  void open();
}

package cn.hz;

/**
 * Define lock as interface
 */
public interface Lock {
    /**
     * Locking method
     */
    public void  lockUp();

    /**
     * Unlocking method
     */
    public void  openLock();

}

package cn.hz;

/**
 * @author hz
 * @version 1.0
 */
public class TheftproofDoor extends  Door implements  Lock{
    @Override
    public void close() {
        System.out.println("Gently pull the door and it closes");
    }

    @Override
    public void open() {
        System.out.println("Push the door hard and the door opens");
    }

    @Override
    public void lockUp() {
        System.out.println("Insert the key, turn it three times to the right, lock it, and pull out the key");
    }

    @Override
    public void openLock() {
        System.out.println("Insert the key, turn it three times to the right, unlock it and pull out the key");
    }
}

package cn.hz;

/**
 * @author hz
 * @version 1.0
 */
public class DoorTest {
    public static void main(String[] args) {
        //Create security door object
        TheftproofDoor door=new TheftproofDoor();
        door.setType("Glass");

        door.openLock();
        door.open();

        door.takePictures();

        door.close();
        door.lockUp();
    }
}

In the above, the anti-theft door is combined by abstract class door and interface lock, so as to improve the scalability of the code. If we need to add a new function to the anti-theft name - doorbell function, we only need to make a doorbell interface:

package cn.hz;

/**
 * Define the interface of a doorbell
 */
public interface DoorBell {
    /**
     * How to define a photo archiving function
     */
    public  void takePictures();
}

As an implementation class, the anti-theft door only needs to implement a new interface, which will not affect our previous content. The code is as follows:

package cn.hz;

/**
 * @author hz
 * @version 1.0
 */
public class TheftproofDoor extends  Door implements  Lock,DoorBell{
    @Override
    public void close() {
        System.out.println("Gently pull the door and it closes");
    }

    @Override
    public void open() {
        System.out.println("Push the door hard and the door opens");
    }

    @Override
    public void lockUp() {
        System.out.println("Insert the key, turn it three times to the right, lock it, and pull out the key");
    }

    @Override
    public void openLock() {
        System.out.println("Insert the key, turn it three times to the right, unlock it and pull out the key");
    }

    @Override
    public void takePictures() {
        System.out.println("card...card....Photo archiving");
    }
}

Through this example, we can see that there are some differences between the use of interfaces and implementation classes. What are their similarities and differences?

4, Comparison between abstract classes and interfaces:

1. Similarities between abstract classes and interfaces:

  • Abstract methods and interfaces cannot be instantiated, but references to abstract classes and interface types can be defined.

2. Grammatical differences:

  • The abstract method in the public class can only provide the details of the abstract method;
  • Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;
  • Interfaces cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods;
  • A class can only inherit one abstract class, while a class can implement multiple interfaces.

3. Differences at the design level:

  • Abstract class is the abstraction of a thing, that is, the abstraction of class, while interface is the abstraction of behavior. Abstract class is to abstract the whole class, including attributes and behaviors, but the interface is to abstract the part (behavior) of the class. For a simple example, aircraft and birds are different kinds of things, but they all have one thing in common, that is, they can Fly. Then, in the design, the aircraft can be designed as an Airplane and the Bird can be designed as a Bird, but the feature of flight cannot also be designed as a class. Therefore, it is only a behavior feature, not an abstract description of a class of things. At this time, the flight can be designed as an interface Fly, including the method fly(), and then Airplane and Bird implement the interface Fly according to their own needs. Then, as for different types of aircraft, such as fighter and civil aircraft, they can directly inherit Airplane, which is similar to birds. Different types of birds can directly inherit Bird. It can be seen from here that inheritance is a yes / no relationship, while interface implementation is a yes / no relationship. If a class inherits an abstract class, the subclass must be the type of the abstract class, and the interface implementation is whether or not it has the relationship, such as whether the Bird can Fly (or whether it has the characteristics of flying). If it can Fly, it can implement the interface, and if it cannot Fly, it will not implement the interface
  • Different from the design level, abstract class, as the parent of many subclasses, is a kind of template design. The interface is a code of conduct, which is a radial design. What is template design? The simplest example is that everyone has used the templates in PPT. If ppt B and PPT C are designed with template a, the common parts of PPT B and PPT C are template A. if their common parts need to be changed, only template a needs to be changed, and there is no need to change ppt B and ppt C again. The radial design, such as an elevator, is equipped with some kind of alarm. Once the alarm is to be updated, it must be updated. In other words, for abstract classes, if you need to add new methods, you can directly add specific implementations to the abstract class, and subclasses can not be changed; Not for the interface. If the interface is changed, all classes that implement the interface must be changed accordingly.

Topics: Java