@TOC

1. Abstract classes

1. Introduction

1.1 Basic Usage

Classes become more concrete as new subclasses are defined in the inheritance hierarchy, while superclasses become more general and generic. Classes should be designed so that the parent and child classes can share characteristics. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class.

  • The abstract keyword is used to modify a class called an abstract class. For example: abstract class A{}

  • The use of abstract modifies a method called abstract method.

    • Abstract method: only method declaration, no method implementation. End with a semicolon: For example:public abstract void talk();

1.2 Anonymous subclasses of abstract classes

The Person class in the following code is an abstract class

Nonanonymous classes Nonanonymous objects

		Worker worker = new Worker();
		method1(worker);// Non-anonymous classes non-anonymous objects
Copy the code

An anonymous object

method1(new Worker());
Copy the code

③ Objects of anonymous subclasses

            Person p = new Person(){//Person is an abstract class and cannot be instantiated
			@Override
			public void eat(a) {
				System.out.println("吃东西"); }}; method1(p);Copy the code

④ Anonymous object of anonymous subclass

method1(new Person(){
			@Override
			public void eat(a) {
				System.out.println("Eat good food."); }});Copy the code

2. Precautions

  • There must be a constructor in the abstract class, which is easy to call when subclass instantiation (involving: subclass object instantiation process)
  • Abstract methods cannot be included in non-abstract classes. If a subclass of an abstract superclass cannot implement all abstract methods, then the subclass must also be defined as abstract. In other words, in the non-abstract subclass of an abstract class extension, all the abstract methods must be implemented. Also note that abstract methods are non-static.
  • You cannot use abstract to modify variables, code blocks, or constructors.
  • You cannot use abstract to modify private methods, static methods, final methods, or final classes. But you can have static methods, which have the advantage of being called directly from the abstract class or subclass name without instantiation
  • An object variable of an abstract class can be defined, but it can only refer to objects of non-abstract classes.In the following code, p is a variable of an abstract class Person that references an instance of a non-abstract subclass Student.
Person p = new Student("John");
Copy the code
  • A subclass can be abstract even if its parent is concrete.

  • You cannot use the new operator to create an instance from an abstract class, but an abstract class can be used as a data class type. Therefore, it is correct to create an array whose elements are of type CeometricObject:

GeometricObject[] objects = new CeometricObject[10];
Copy the code
You can then create an instance of a CeometricObject and give the reference values to the array as follows:Copy the code
objects[0] =newCircle ();Copy the code

The code for constructors and static methods is as follows:

abstract class AbstractClass{
    /** * output */
    abstract void print(a);

    / * * * * /
    public AbstractClass(a) {// Constructors can be defined in abstract classes, although they cannot be initialized and can be inherited by subclasses
        System.out.println("abstract class");
    }
    public static void staticAbstractMethod(a) {
        System.out.println("I am static method"); }}/ * * *@author sir
 */
public class AbstractClassTest extends AbstractClass{
    public AbstractClassTest(a) {
        System.out.println("Subclass constructor");
    }
    @Override
    void print(a) {
        System.out.println("test");
    }
    public static void main(String[] args) {
        AbstractClassTest.staticAbstractMethod();// Static methods can be defined in abstract classes, which can be called directly from the class name
        AbstractClass.staticAbstractMethod();
        newAbstractClassTest().print(); }}Copy the code

Output result:

2. Interface

1. Introduction

1.1 Basic Usage

An interface is a class-like structure that resembles an abstract class in many ways, but its purpose is to indicate the common behavior of multiple objects of related or unrelated classes. An interface is a specification that defines a set of rules that represent the real world “if you are/want to… Must be able to…” Thoughts. Inheritance is a “no” relationship, whereas interface implementation is a “no” relationship. Grammar:

The modifierinterfaceThe interface name{
 /** Constant declaration */
  /** Method signature */
}
Copy the code

Define the syntax format of a Java class: extends, implements

 class SubClass extends SuperClass implements InterfaceA{}Copy the code
  • Interface cannot define a constructor! Means that the interface cannot be instantiated.
  • In Java development, interfaces are created by allowingClass to implement. The relationship between a class and an interface is called interface inheritance. Because interface inheritance and class inheritance are essentially the same, we call them both inheritance for short.If the implementation class overrides all the abstract methods in the interface, then the implementation class can be instantiated. If the implementation class does not override all of the abstract methods in the interface, the implementation class remains an abstract class.
  • Java classes can implement multiple interfaces, making up for the limitations of Java’s single inheritanceFormat:class AA extends BB implements CC,DD,EE
  • Interfaces can be inherited from one another, and multiple interfaces can be inherited

1.2 Comparison between interfaces and abstract classes

Example interface:

public class USBTest {
    public static void main(String[] args) {

        Computer computer = new Computer();
        //1. Create a non-anonymous object for the non-anonymous implementation class of the interface
        Flash flash = new Flash();
        computer.transferData(flash);

        //2. Create an anonymous object for the non-anonymous implementation class of the interface
        computer.transferData(new Printer());

        //3. Create a non-anonymous object for the anonymous implementation class of the interface
        USB phone = new USB(){

            @Override
            public void start(a) {
                System.out.println("Cell phone starts working.");
            }

            @Override
            public void stop(a) {
                System.out.println("Phone off the clock."); }}; computer.transferData(phone);//4. Create an anonymous object for the anonymous implementation class of the interface

        computer.transferData(new USB(){
            @Override
            public void start(a) {
                System.out.println("Mp3 to work");
            }

            @Override
            public void stop(a) {
                System.out.println("Mp3 finished work"); }}); }}class Computer{

    public void transferData(USB usb){//USB usb = new Flash();
        usb.start();

        System.out.println("Details of the transmission."); usb.stop(); }}interface USB{
    // Constant: defines the length, width, maximum and minimum transmission speed, etc

    void start(a);

    void stop(a);

}

class Flash implements USB{

    @Override
    public void start(a) {
        System.out.println("Usb flash drive start operation");
    }

    @Override
    public void stop(a) {
        System.out.println("The usb flash drive is finished."); }}class Printer implements USB{
    @Override
    public void start(a) {
        System.out.println("Printer start up");
    }

    @Override
    public void stop(a) {
        System.out.println("Printer finished working"); }}Copy the code

1.3 New JDK8 Interface features

In Java 8, you can add static and default methods to an interface. Technically, this is perfectly legal, but it seems to violate the idea of an interface as an abstract definition.

  • Static method:Use the static keyword. You can call a static method directly through an interface and execute its method body.We often use static methods in classes that we use together. You can find pairs of interfaces and classes like Collection/Collections or Path/Paths in the standard library.
  • Default method:The default method is decorated with the default keyword. It can be called by implementing class objects.We provide new methods in existing interfaces while maintaining compatibility with older versions of the code. For example, the Java 8 API provides rich default methods for Collection, List, Comparator, and so on.
  • If a default method is defined in one interface and a method with the same name and parameter is defined in another interface (whether or not the method is the default method), it will occur when the implementation class implements both interfaces:Interface conflict.
    • Solutions:Implementation classes must override methods with the same name and parameter in the interface to resolve conflicts.
  • If a default method is defined in an interface and a nonabstract method with the same name and parameters is defined in the parent class, there will be no conflicts. Because at this time observe:Principle of precedence of class. Default methods with the same name and parameters in the interface are ignored
public interface CompareA {
	
	// Static method
	public static void method1(a){
		System.out.println("CompareA: Beijing");
	}
	// The default method
	public default void method2(a){
		System.out.println("CompareA: Shanghai");
	}
	
	default void method3(a){
		System.out.println("CompareA: Shanghai"); }} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *public interface CompareB {
	
	default void method3(a){
		System.out.println("CompareB: Shanghai"); }}public class SuperClass {
	
	public void method3(a){
		System.out.println("SuperClass: Beijing"); }} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *public class SubClassTest {
	
	public static void main(String[] args) {
		SubClass s = new SubClass();
		
// s.method1();
// SubClass.method1();
		// Static methods defined in the interface can only be called through the interface.
		CompareA.method1();
		By implementing class objects, you can call the default methods in the interface.
		// If the implementation class overrides the default method in the interface, it still calls the overridden method
		s.method2();
		If a subclass (or implementation class) inherits a parent class and implements an interface that declares a default method with the same name and argument,
		// By default, a subclass calls a method with the same name and argument as the parent class without overriding this method. --> Class priority
		// If the implementation class implements multiple interfaces that define default methods with the same name and argument,
		// An error is reported if the implementation class does not override this method. --> Interface conflict.
		// This requires that we override this method in the implementation classs.method3(); }} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *class SubClass extends SuperClass implements CompareA.CompareB{
	
	public void method2(a){
		System.out.println("SubClass: Shanghai");
	}
	
	public void method3(a){
		System.out.println("SubClass: Shenzhen");
	}
	
	// How to call a method in a subclass (or implementation class) that is overridden in an interface
	public void myMethod(a){
		method3();// Call your own overridden method
		super.method3();// the call is declared in the parent class
		// Invoke the default method in the interface
		CompareA.super.method3();
		CompareB.super.method3(); }}Copy the code

Output result:

2. The Comparable interface

2.1 usage

  1. The Comparable interface defines the compareTo method for comparing objects
  2. The compareTo method determines the order of the object relative to the given object O, and returns a negative integer, 0, or positive integer when the object is less than, equal to, or greater than the given object O, respectively.
  3. The Comparable interface is a generic interface. When implementing the interface, the generic type E is replaced with a concrete type.
  4. Many classes in the Java class library implement the Comparable interface to define the natural order of objects. Byte, Short, Integer, Long, Float, Double, Character, Biglnteger, BigDecimalx Calendar, String, and Date classes all implement the Comparable interface.
import java.util.Date;

/ * * *@author mazouri
 * @createThe 2020-04-12 summer * /
public class CompareTest {
    public static void main(String[] args) {
        System.out.println((new Integer(3).compareTo(new Integer(5))));
       // System.out.println((Integer.compare(3, 5))); There's certainly a better way to do it
        System.out.println("ABC".compareTo("ABE"));
        Date date1 = new Date(1990.1.1);
        Date date2 = new Date(1989.6.4); System.out.println(date1.compareTo(date2)); }}Copy the code

Output result:

2.2 Custom implement Comparable classes for comparison

Title: Define an interface to implement the comparison of two objects. interface CompareObject{ public int compareTo(Object o); // If the return value is 0, equal; If the value is positive, it indicates that the previous object is large. } defines a Circle class, declares width, height properties, provides getter and setter methods and defines a ComparableRectangle. Class, inheriting the Rectangle class and implementing the CompareObject interface. The interface’s compareTo method is given in the ComparableCircle class to compare the area sizes of two rectangles. Define a test class ComparableRectangleTest, create two ComparableRectangle objects, and call the compareTo method to compare the areas of the two classes.

public interface CompareObject<C extends Rectangle> {
    / * * *@returnIf the return value is 0, it is equal. If the value is positive, the current object is large. A negative number represents a small */ for the current object
    int compareTo(Object o); } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *public class Rectangle {
    private double width;
    private double height;

    public Rectangle(a) {}public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getWidth(a) {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight(a) {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    public double getArea(a) {
        returnheight * width; }} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *public class ComparableRectangle extends Rectangle implements CompareObject {
    public ComparableRectangle(a) {}public ComparableRectangle(double width, double height) {
        super(width, height);
    }

    @Override
    public int compareTo(Object o) {
        if (this == o) {
            return 0;
        }

        if (o instanceof ComparableRectangle) {
            ComparableRectangle c = (ComparableRectangle) o;
            // return Double.compare(getArea(), c.getArea());
            if (getArea() > c.getArea()) {
                return 1;
            } else if (getArea() < c.getArea()) {
                return -1;
            } else {
                return 0; }}else {
            throw new RuntimeException("Incoming data types do not match"); }}} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *public class ComparableRectangleTest {
    public static void main(String[] args) {
        ComparableRectangle c1 = new ComparableRectangle(2.2.3.4);
        ComparableRectangle c2 = new ComparableRectangle(2.3.3.4);

        int compareValue = c1.compareTo(c2);
        if (compareValue > 0) {
            System.out.println("C1 object is large");
        } else if (compareValue < 0) {
            System.out.println("C2 object large");
        } else {
            System.out.println("C1 is the same size as C2"); }}}Copy the code

Output result:

Inner class

1. Introduction

  • When there is an internal part of a thing that needs to be described by a complete structure that only serves the external thing, then the entire internal complete structure is best used by the inner class.
  • In Java, the definition of one class is allowed to reside inside another class, called an inner class and an outer class.

Class: ① Inner class (static inner class and non-static inner class) ② Local inner class (not talking about modifiers), anonymous inner class

2. Local inner classes

2.1 Basic Usage

A Java local inner class is a class defined in a method that is only valid in that method.

classOutside class{{method ()classLocal inner class{{}}classLocal inner class{}}}Copy the code

2.2 How to Use local inner classes:

  • Use it only in the method or block of code that declares it, and use it first and then. You can’t use this class anywhere else
  • But its objects can be returned using the return value of an external method. The return value type can only be the parent or parent interface type of a local inner class

2.3 Characteristics of local inner classes

  • The inner class is still a separate class. After compilation, the inner class is compiled into a separate.class file, but it is preceded by the outer class’s class name, $symbol, and numeric number.
  • Use it only in the method or block of code that declares it, and use it first and then. You can’t use this class anywhere else.
  • Local inner classes can use members of external classes, including private ones.
  • Local inner classYou can use local variables of external methods, but they must be final.Due to the different declaration cycles of local inner classes and local variables.
    • JDK 7 and earlier: Requires that this local variable be explicitly declared final
    • JDK 8 and later: You can omit final declarations
  • Local inner classes have similar status to local variables and cannot use public,protected, default, or private
  • Local inner classes cannot use static decorations and therefore cannot contain static members

Anonymous inner classes

3.1 Basic Usage

An anonymous inner class cannot define any static members, methods, or classes. Only one instance of an anonymous inner class can be created. An anonymous inner class must be used after new to implicitly implement an interface or implement a class. Format:

New parent constructor (argument list) implementation interface (){// Body part of anonymous inner class}Copy the code
interface A{
public abstract void fun1(a);
}
public class Outer{
public static void main(String[] args) {
new Outer().callInner(new A(){
// The interface cannot be new, but the special case here is that the subclass object implements the interface, but does not give the object a name
public void fun1(a) {System. Out. Println (" implementfor fun1"); }}); } public void callInner(A A) {a.fun1(); }}Copy the code

3.2 Characteristics of anonymous inner classes

  • An anonymous inner class must inherit from a parent class or implement an interface
  • Anonymous inner classes can have only one object
  • Anonymous inner class objects can only be referenced in polymorphic form

4. Member inner classes

4.1 Member Inner Class’s role as a member of a class:

  • Unlike external classes, Inner classes can also be declared private or protected;
  • The structure of an external class can be invoked
  • Inner classes can be declared static, but non-static member variables of outer classes cannot be used.

4.2 Roles of member inner Classes as classes:

  • You can define properties, methods, constructors, and so on internally
  • Can be declared as an abstract class and therefore can be inherited by other inner classes
  • You can declare it final
  • OuterClass$innerClass. class bytecode file (also available for local inner classes)

Pay attention to

  1. A member of a non-static member inner class cannot be declared static. A member can be declared static only in an outer class or a static member inner class.
  2. An external class accessing a member of an inner class requires an inner class. Member or inner class. Object. Member”
  3. Member inner classes can directly use all members of the external class, including private data
  4. When you want to use an inner class for the static member part of an outer class, consider declaring the inner class static
public class InnerClassTest {
	public static void main(String[] args) {
		
		// Create Dog instance (static member inner class):
		Person.Dog dog = new Person.Dog();
		dog.show();
		// Create Bird instance (non-static member inner class):
// Person.Bird bird = new Person.Bird(); / / error
		Person p = new Person();
		Person.Bird bird = p.new Bird(a);
		bird.sing();
		
		System.out.println();
		
		bird.display("Orioles"); }}class Person{
	
	String name = "Xiao Ming";
	int age;
	
	public void eat(a){
		System.out.println("People: Eat.");
	}
	
	
	// Static member inner class
	static class Dog{
		String name;
		int age;
		
		public void show(a){
			System.out.println("Carla is a dog.");
// eat();}}// Non-static member inner class
	class Bird{
		String name = "Cuckoo";
		
		public Bird(a){}public void sing(a){
			System.out.println("I am a little bird");
			Person.this.eat();// Invoke the non-static properties of the external class
			eat();
			System.out.println(age);
		}
		
		public void display(String name){
			System.out.println(name);// Parameter to the method
			System.out.println(this.name);// Inner class attributes
			System.out.println(Person.this.name);// Attributes of the external class}}}Copy the code

Output result: