Abstract classes and abstract methods: abstract

Use of the abstract keyword

Structures that can be modified by abstract: classes and methods, but private methods, static methods, and final-modified classes and methods cannot be modified.
final: prohibit inheritance and rewrite. abstract: Encourage inheritance and rewrite.

abstract modified class: abstract class

  1. This class cannot be instantiated
  2. There must be a constructor in the abstract class, which is convenient to call when the subclass is instantiated
  3. During development, subclasses of abstract classes will be provided, and subclass objects can be instantiated to complete related operations.

abstract modification method: abstract method

  1. Abstract methods have only declarations, no method bodies, and cannot be called.
  2. A class containing abstract methods must be an abstract class, and an abstract class does not necessarily have abstract methods.
  3. If the subclass overrides all the abstract methods of the abstract parent class, the subclass can be instantiated. Otherwise, this subclass is also an abstract class.

Anonymous subclass, understanding of anonymous objects

  1. Calls not assigned to the class -> Anonymous object
  2. Did not create a new subclass to inherit the parent abstract class -> anonymous subclass
public class AbstractTest {
    
    
    public static void main(String[] args) {
    
    
        method(new Student());//非匿名子类的匿名对象

        Student s = new Student();
        method(s);//非匿名子类的非匿名对象


        Person p = new Person() {
    
    
            @Override
            public void sleep() {
    
    
                System.out.println("sleep");
            }
        };
        method(p);//匿名子类的非匿名对象

        method(new Person() {
    
    
            @Override
            public void sleep() {
    
    
                System.out.println("sleep");
            }
        });//匿名子类的匿名对象
    }

    public static void method(Person p){
    
    
        System.out.println("method");
    }
}

//抽象类
abstract class Person {
    
    
    String name;
    int age;

    public Person() {
    
    

    }

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

    public void eat() {
    
    
        System.out.println("eat");
    }

    public void walk() {
    
    
        System.out.println("walk");
    }
    //抽象方法
    public abstract void sleep();
}

class Student extends Person {
    
    
    @Override
    public void sleep() {
    
    

    }
}

Guess you like

Origin blog.csdn.net/AmorFati1996/article/details/108719437