Related articles:

  1. Object Orientation revisited: Introduces the basic concepts of object orientation
  2. Object creation in Java: introduces the creation of objects, the use of constructors
  3. Java Inheritance issues: introduces the use of inheritance and considerations

This article introduces the use of Java abstract classes and interfaces.

1. An abstract class

As mentioned in the previous article, a parent class is more abstract, and a child class is more concrete than its parent class.

Examples of animals and dogs are given in the article “Java Inheritance Issues” :

public class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Animal(a) {}public void say(a) {
        System.out.println("I am" + name + "This year" + age + "Old");
    }

	//getters and setters ...
}
Copy the code
public class Dog extends Animal {

    private String address;

    public Dog(String name, int age, String address) {
        super(name, age);
        this.address = address;
    }

    public Dog(a) {}public void say(a) {
        System.out.println("My name is" + super.getName() + "This year" + super.getAge() + "I'm old and I live at home." + address + "Woof woof woof...");
    }

    public void watchDoor(a) {
        System.out.println("I am" + address +"Guard...");
    }

	//getters and setters ...
}
Copy the code

Dog is a natural successor to Animal. But consider the Animal say() method.

An animal is a very broad concept, and if you code it, most of the creatures we see can inherit from it. The diagram below:

Animal say() = Animal say() = Animal Because every Animal has a different way of speaking, and animals are such a broad concept, we usually use new Dog() or new People(), but rarely new Animal().

So the say() method body of the Animal class is useless because it will be overridden by its subclasses. In this case, simply don’t use the method body.

In other words, we take Animal to a higher level of abstraction, it has properties that all animals have, like name and age, and it has behaviors that all animals have, like say. However, the Animal class does not implement this method; the implementation is left to subclasses.

In this way, whoever inherits from the Animal class has its properties and behavior, and the subclass doesn’t care if the behavior of the parent class is appropriate, because the behavior of the parent class is “nominal”, so the subclass only needs to inherit these “names”, and the concrete “real” is completed by the subclass.

This Animal class is an abstract class.

Now change the Animal class to abstract, and leave the Dog class unchanged:

public abstract class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {// Has a parameter constructor
        this.name = name;
        this.age = age;
    }

    public Animal(a) {// No parameter constructor
    }

    public abstract void say(a);// Abstract methods

    
    public String getName(a) {// The method to be implemented
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
	//getters and setters..
}
Copy the code

Here are the characteristics of abstract classes:

(a) The abstract class is modified by the abstract keyword.

public abstract class Animal {
    / /...
}
Copy the code

(2) A class with no method body is called abstract.

public abstract void say(a);// Abstract methods
Copy the code

(c) A class with abstract methods must be abstract.

(4) A class without abstract methods can also be abstract.

(5) An abstract class may have member variables, constructors, and methods that are implemented concretely. Constructors cannot be abstract.

(6) An abstract class cannot be instantiated, but an abstract class variable can be declared

Animal animal = new Animal();// error: 'Animal' is abstract; cannot be instantiated
Anima animal;// Abstract class variables, available
Copy the code

The classes we encountered before, such as the Dog class, were used to describe objects, but the methods of the abstract class did not have a concrete implementation, so it did not have enough information to describe objects, so the abstract class could only be inherited to describe its subclasses, not instantiated.

(7) Subclasses have two options for extending abstract parent classes:

  1. When a subclass is not abstract, the subclass must implement the abstract methods of its abstract parent:
public class Dog extends Animal {
	// Attributes, constructors, other methods
    
    // Implement the abstract method of the abstract superclass
    @Override
    public void say(a) {
        System.out.println("My name is" + super.getName() + "This year" + super.getAge() + "I'm old and I live at home." + address + "Woof woof woof..."); }}Copy the code
  1. When a subclass is abstract, the subclass can implement the abstract methods of the abstract parent or choose not to implement them.
public abstract class Dog extends Animal {
    // Attributes, constructors, other methods
    
    // You can choose not to implement abstract methods of the parent class
}
Copy the code

2. The interface

2.1. What is an interface?

In life, there is a kind of interface that we use every day, that is the socket.

No matter what kind of electrical appliances, refrigerators, televisions, computers, electric fans, as long as you buy them, you can plug them in. Is so convenient, because electrical appliance producers and manufacturers to comply with a socket production specification: I put the socket production into this appearance, you put the plug into the production, I don’t care you electrical appliances inside is what, you don’t have to tube socket inside is what, good product production, each sold to customers, cooperate happily, together make money. If these products break down in the future, you can buy another one to comply with the specifications and continue to use.

Think about it, if there is no specification, socket and plug production of strange, buy back how to use? Can disassemble socket and refrigerator only, connect 220V wire with hand.

In other words, an interface is a production specification/standard, or an agreement to be followed by both parties, and as long as both parties follow it, they can communicate happily and cooperate happily.

In Java development, a software system is definitely not built by one person, but by a team. So how do you avoid that class B written by A doesn’t work, and class C written by B doesn’t work, so that a changes the code of B, and B changes the code of C? Set up a specification (interface) in advance, everyone obeys the interface, as long as I know your interface, then I don’t need to know your specific code, can call your class.

2.2. Use of interfaces

Learn a few features about interfaces and you can write interfaces happily:

Inteface (); inteface (); inteface ();

public interface Runnable {}Copy the code

(2) Interface usually write a variety of abstract methods, but only declare, can not write method body.

public interface Runnable {
    /*public abstract*/ void run(a);
}
Copy the code

(3) You do not have to declare methods as public abstract. All methods in the interface default to the public abstract modifier.

(4) The interface can not have member variables, static code blocks.

(5) The interface can contain constants. By default, constants are public static final.

public interface Runnable {
   /*public static final*/ int i = 1;
    void run(a);
}
Copy the code

A class implements an interface through the implements keyword. It must implement all methods in the interface as well.

public class Dog implements Runnable {
    @Override
    public void run(a) {
        System.out.println("Run fast.");
    }
    
    / /...
}
Copy the code

(7) If the class implementing the interface is an abstract class, it is not necessary to implement the methods in the interface.

(8) A class may inherit both classes and implement interfaces.

public class Dog extends Animal implements Runnable {
    / /...
}
Copy the code

(9) A class can implement more than one interface.

public class Dog implements Runnable.Flyable {
    / /...
}
Copy the code

(10) Interfaces can inherit, and allow multiple inheritance.

public interface A {
    / /...
}

public interface B extends A.Runnable{
    / /...
}
Copy the code

An interface cannot be instantiated, but an interface variable can be declared.

Runnable runnable = new Runnable();//'Runnable' is abstract; cannot be instantiated
Runnable runnable;// Interface variable, available
Copy the code

3. Summary

Abstract classes are declared with the abstract keyword. In addition to abstract methods (declared with the abstract keyword), abstract classes can also have member variables, constructors, and methods of ordinary classes. Cannot be instantiated, but can declare variables of an abstract class. A subclass inherits an abstract class that implements the abstract methods of its parent (if the subclass is abstract, no implementation is required).

Interfaces are declared with the interface keyword and can have only abstract methods and constants (modifiers are ignored). Cannot be instantiated, but can declare interface variables. Interfaces can inherit from one another, and multiple inheritance is allowed. Class implementation interfaces use the implements keyword, and must implement abstract methods in the interface (not if the class is abstract).

After summarizing the characteristics of abstract classes and interfaces, it seems that abstract classes can also be used as interfaces. So why have interfaces when you have abstract classes?

Classes can only be inherited singly. Using an abstract class as an “interface” means that a class can only obey one “interface”, which is obviously not practical. Interfaces are much more flexible.

4. About me

Please correct me if there are any mistakes.