Java se -- abstract classes and interfaces

Posted by markwillis82 on Sun, 26 Dec 2021 13:28:14 +0100

abstract class

summary

Abstract class introduction

The method in the parent class is overridden by its subclasses, and the implementation of subclasses is different. Then the method declaration and method body of the parent class only have meaning, while the method body has no meaning (because the subclass object will call its own overridden method). In other words, the parent class may know which function the child class should have, However, it is not clear how the function implements the parent class (determined by the child class). The parent class only needs to provide a definition without method body, and the specific implementation is left to the child class to implement. We call the method without method body abstract method. Java syntax stipulates that the class containing abstract method is abstract class.

  • Abstract method: a method without a method body.
  • Abstract class: a class that contains abstract methods.

abstract use format

Abstract means Abstract. It is used to modify methods and classes. Modified methods are abstract methods and modified classes are abstract classes.

Abstract method

Using the abstract keyword to modify a method, the method becomes an abstract method. The abstract method contains only a method name and no method body.

Define format:

Modifier  abstract Return value type method name (parameter list);

Code example:

public abstract void run();

abstract class

If a class contains abstract methods, the class must be abstract. Note: abstract classes do not necessarily have abstract methods, but classes with abstract methods must be defined as abstract classes.

Define format:

abstract class Class name { 
  
}

Code example:

public abstract class Animal {
    public abstract void run();
}

Use of abstract classes

Requirement: subclasses that inherit abstract classes must override all abstract methods of the parent class. Otherwise, the subclass must also be declared as an abstract class.

Code example:

// Abstract class
abstract class Employee {
	private String id;
	private String name;
	private double salary;
	
	public Employee() {
	}
	
	public Employee(String id, String name, double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	
	// Abstract method
	// Abstract methods must be placed in abstract classes
	abstract public void work();
}

// Define a subclass to inherit an abstract class
class Manager extends Employee {
	public Manager() {
	}
	public Manager(String id, String name, double salary) {
		super(id, name, salary);
	}
	// 2. Override the abstract method of the parent class
	@Override
	public void work() {
		System.out.println("Manage others");
	}
}

// Define a subclass to inherit an abstract class
class Cook extends Employee {
	public Cook() {
	}
	public Cook(String id, String name, double salary) {
		super(id, name, salary);
	}
	@Override
	public void work() {
		System.out.println("Cook fry vegetables with more salt...");
	}
}

// Test class
public class Demo10 {
	public static void main(String[] args) {
		// Create an abstract class. An abstract class cannot create an object
		// Suppose the abstract class lets us create an object. The abstract method in it has no method body and cannot be executed So let's not create objects
//		Employee e = new Employee();
//		e.work();
		
		// 3. Create subclasses
		Manager m = new Manager();
		m.work();
		
		Cook c = new Cook("ap002", "Cook", 1);
		c.work();
	}
}

The method rewriting at this time is the completion and implementation of the parent class's abstract method by the subclass. The operation of rewriting this method is also called the implementation method.

Characteristics of abstract classes

The characteristics of abstract classes can be said to have gains and losses

Yes: abstract classes get the ability to have abstract methods.

Loss: abstract classes lose the ability to create objects.

Other members (construction methods, instance methods, static methods, etc.) are abstract classes.

Details of abstract classes

You don't need to memorize it. Just know how to modify it after the idea reports an error.

As for the use of abstract classes, the following are the details that should be paid attention to in syntax. Although there are many items, if you understand the essence of abstraction, you don't need to memorize by rote.

  1. An abstract class cannot create an object. If it is created, the compilation fails and an error is reported. Only objects whose non Abstract subclasses can be created.

    Understanding: suppose an object of an abstract class is created and an abstract method is called, but the abstract method has no specific method body and has no meaning.

  2. Abstract classes can have construction methods, which are used to initialize parent class members when subclasses create objects.

    Understanding: in the subclass constructor, there is a default super(), which needs to access the parent constructor.

  3. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.

    Understanding: an abstract class that does not contain an abstract method is intended to prevent the caller from creating this class object. It is usually used for some special class structure design.

  4. The subclass of an abstract class must override all abstract methods in the abstract parent class, otherwise the subclass must also be defined as an abstract class, and an error will be reported if the compilation fails.

    Understanding: assuming that all abstract methods are not overridden, the class may contain abstract methods. After creating objects, it is meaningless to call abstract methods.

  5. Abstract classes exist in order to be inherited by subclasses.

    Understanding: what has been implemented in the abstract class is the members determined in the template. The abstract class is not sure how to implement. It is defined as an abstract method and handed over to a specific subclass for implementation.

Significance of abstract class existence

Abstract classes exist in order to be inherited by subclasses. Otherwise, abstract classes will be meaningless. Abstract classes can force subclasses to be overridden according to the specified format.

Chapter V interface

summary

We have learned about abstract classes. Abstract methods can be used in abstract classes, as well as ordinary methods, construction methods, member variables, etc. So what is an interface? Interfaces are more thorough abstractions. Before JDK7, including JDK7, interfaces are all abstract methods. Interfaces also cannot create objects.

Define format

//Interface definition format:
interface Interface name{
    // Abstract method
}

// Declaration of interface: Interface
// Interface name: initial capital, meeting "Hump mode"

Characteristics of interface components

Before JDK7, including JDK7, the interface only contained abstract methods and constants

Abstract method

Note: the abstract methods in the interface will be automatically decorated with public abstract by default. Programmers do not need to write by themselves!!
According to the specification: it is recommended not to write public abstract for future abstract methods in the interface. Because it's not necessary, it will be added by default.

constant

The member variables defined in the interface will be decorated with: public static final by default. That is, the member variable defined in the interface is actually a constant. Here, after public static final modification is used, the variable value cannot be modified, and the static variable can be accessed directly with the interface name, so it is also called a constant. Constants must be given initial values. Constant naming conventions recommend that all letters be capitalized and multiple words be underlined.

Case demonstration

public interface InterF {
    // Abstract method!
    //    public abstract void run();
    void run();

    //    public abstract String getName();
    String getName();

    //    public abstract int add(int a , int b);
    int add(int a , int b);


    // Its final wording is:
    // public static final int AGE = 12 ;
    int AGE  = 12; //constant
    String SCHOOL_NAME = "Dark horse programmer";

}

Basic implementation

Overview of implementation interface

The relationship between class and interface is implementation relationship, that is, class implements interface. This class can be called implementation class of interface or subclass of interface. The implemented actions are similar to inheritance and the format is similar, but the keywords are different. The implementation uses the implements keyword.

Format of implementation interface

/**Implementation of interface:
    In Java, the interface is implemented, and the class that implements the interface is called the implementation class.
    Format of implementation class:*/
class Class name implements Interface 1,Interface 2,Interface 3...{

}

As can be seen from the above format, the interface can be implemented by multiple users. You can think about why?

Requirements and significance of class implementation interface

  1. You must override all abstract methods in all interfaces implemented.
  2. If a class implements an interface but does not rewrite all the abstract methods of all interfaces, the class must also be defined as an abstract class.
  3. Meaning: an interface embodies a specification. An interface is a mandatory constraint on the implementation class. Either all the functions declared by the interface are completed, or it is defined as an abstract class. This is a mandatory norm.

Basic implementation cases of classes and interfaces

If we define an athlete's interface (specification), the code is as follows:

/**
   Interface: the interface reflects the specification.
 * */
public interface SportMan {
    void run(); // Abstract methods, running.
    void law(); // Abstract methods, abide by the law.
    String compittion(String project);  // Abstract methods, competition.
}

Next, define a table tennis player class and implement the interface. The implementation class code of the interface is as follows:

package com.itheima._03 Implementation of interface;
/**
 * Implementation of interface:
 *    In Java, the interface is implemented, and the class that implements the interface is called the implementation class.
 *    Format of implementation class:
 *      class Class name implements interface 1, interface 2, interface 3 {
 *
 *
 *      }
 * */
public class PingPongMan  implements SportMan {
    @Override
    public void run() {
        System.out.println("Table tennis players run a little!!");
    }

    @Override
    public void law() {
        System.out.println("Table tennis players obey the law!");
    }

    @Override
    public String compittion(String project) {
        return "participate in"+project+"Win the gold medal!";
    }
}

Test code:

public class TestMain {
    public static void main(String[] args) {
        // Create an implementation class object.
        PingPongMan zjk = new PingPongMan();
        zjk.run();
        zjk.law();
        System.out.println(zjk.compittion("Global table tennis competition"));

    }
}

Multiple implementation cases of classes and interfaces

The relationship between classes and interfaces is multi implemented. A class can implement multiple interfaces at the same time.

First, we define two interfaces. The code is as follows:

/** Legal specification: Interface*/
public interface Law {
    void rule();
}

/** This is an athlete's specification: interface*/
public interface SportMan {
    void run();
}

Then define an implementation class:

/**
 * Java Interfaces in can be implemented in multiple ways:
 *    A class can implement multiple interfaces: Law, SportMan
 *
 * */
public class JumpMan implements Law ,SportMan {
    @Override
    public void rule() {
        System.out.println("Respect elders and abide by the law");
    }

    @Override
    public void run() {
        System.out.println("Train and run!");
    }
}

It can be seen from the above that classes and interfaces can be implemented in multiple ways. We can understand that it is reasonable to implement multiple specifications.

Interface and interface multi inheritance

In Java, interfaces can inherit from one another: that is, an interface can inherit multiple interfaces at the same time. You must pay attention to:

Classes and interfaces are implementation relationships

Interface and interface are inheritance relationships

Interface inheriting interface is to merge the abstract methods of other interfaces with this interface.

Case presentation:

public interface Abc {
    void go();
    void test();
}

/** Legal specification: Interface*/
public interface Law {
    void rule();
    void test();
}

 *
 *  Summary:
 *     There are multiple implementations between interfaces and classes.
 *     There are multiple inheritance between interfaces.
 * */
public interface SportMan extends Law , Abc {
    void run();
}

Interface details

You don't need to memorize it. Just know how to modify it after the idea reports an error.

As for the use of interfaces, the following are the details that should be paid attention to in syntax. Although there are many items, if you understand the essence of abstraction, you don't need to memorize by rote.

  1. What should I do when the same abstract method exists in two interfaces?

Just rewrite it once. At this time, the rewritten method means rewriting both 1 interface and 2 interface.

  1. Can the implementation class inherit class A and implement other interfaces at the same time?

An inherited parent is like a father
The interface implemented is like Godfather
You can inherit a class and implement multiple interfaces at the same time, but you should implement all the abstract methods in the interface.

  1. Can an implementation class inherit an abstract class and implement other interfaces at the same time?

The implementation class can inherit an abstract class and implement multiple other interfaces at the same time, but it only needs to rewrite all the abstract methods inside.

  1. The implementation class Zi implements an interface and inherits a Fu class. Suppose there is a method in the interface and the same method in the parent class. How do subclasses operate?

Solution 1: if the method body in the parent class can meet the needs of the current business, it can be rewritten in the subclass.
Solution 2: if the method body in the parent class cannot meet the requirements of the current business, it needs to be rewritten in the subclass.

  1. What if there are 10 abstract methods in an interface, but I only need to use one of them in the implementation class?

You can create an intermediate class (adapter class) between the interface and the implementation class
Let the adapter class implement the interface and short rewrite all the methods in the interface.
Let the subclass inherit the adapter class and override which method you want to use.
Because intermediate classes have no practical significance, they are generally defined as abstract and do not allow the outside world to create objects
Privatized constructor - reflection. Even if the constructor is privatized, objects can be created outside

Exercise interface: developing printers

  • Cartridge: black and white, color (connector)
  • Paper type: A4, B5
  • Ink cartridges and paper are not provided by the printer manufacturer
  • The printer should be compatible with ink cartridges and paper on the market

The output interfaces are as follows:

public class Computer {
    Inter i =new Inter();
    Seagate s =new Seagate();
    Kingston k = new Kingston();
    public void show(){
        System.out.println("The computer information is as follows:");
        System.out.println("CPU Our brands are:"+i.getBrand()+",The dominant frequency is: 3.8GHZ");
        System.out.println("The hard disk capacity is:"+s.getDiskCapacity());
        System.out.println("Memory capacity is:"+k.getRamCapacity());
    }
}
public interface Cpu {
    String getBrand();
}
public interface HardDisk {
    String getDiskCapacity();
}
public class Inter implements Cpu{
    @Override
    public String getBrand() {
        return "Inter";
    }
}
public class Kingston implements Ram{
    @Override
    public String getRamCapacity() {
        return "8GB";
    }
}
public interface Ram {
    String getRamCapacity();
}
public class Seagate implements HardDisk{
    @Override
    public String getDiskCapacity() {
        return "Solid state 1 T";
    }
}
public class Test {
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.show();
    }
}

Topics: Java Back-end OOP interface JavaSE