Java is in hand, I have the world! ! ! Java-abstract methods and abstract classes

definition

Abstract method: just add abstractkeywords, then remove the braces, and end with a semicolon;
abstract class: the class where the abstract method is located must be an abstract class. In the classprior written on the abstractcan.

How to use abstract classes and abstract methods:
[1] Cannot create newabstract class objects directly .
[2] A subclass must be used to inherit the abstract parent class.
[3] The subclass must override all abstract methods in the abstract parent class.
Override (implementation): The subclass removes the abstractkeyword of the abstract method , and then adds the method body braces.
[4] Create subclass objects for use

Code example

public abstract class Animal {
    
    
    //这是一个抽象方法,代表吃东西,但是具体吃什么(大括号中的内容)不确定
    public abstract void eat();

    //这是普通的成员方法
    public void normalMethod(){
    
    
    }
}

public class Cat extends Animal{
    
    
    @Override
    public void eat(){
    
    
        System.out.println("猫吃鱼");
    }
}

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

          //抽象类不能直接new创建
//        Animal animal=new Animal();
          //创建子类对象使用
          Cat cat=new Cat();
          cat.eat();
    }
}

Notes on the use of abstract classes:

  1. Abstract classes cannot create objects. If they are created, an error will be reported because the compilation fails. Only objects of non-abstract subclasses can be created.
    2. In the abstract class, there can be a construction method, which is used to initialize the members of the parent class when the subclass creates an object. In other words, there is a default in the subclass's construction method super(), which requires access to the parent's construction method.
  2. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
  3. The subclass of the abstract class must rewrite all the abstract methods in the abstract parent class, otherwise, the compilation fails and an error is reported. Unless the subclass is also an abstract class.
    Understanding: Assuming that all abstract methods are not rewritten, the class may contain abstract methods. Then after creating the object, calling the abstract method does not make sense.

Guess you like

Origin blog.csdn.net/wtt15100/article/details/108120200
Recommended