Java---abstract classes and interfaces

Java—abstract classes and interfaces

One, abstract class

Keywordabstract,inherit:extends
Insert picture description here
Why use abstract classes? The reason is: when a method of the parent class needs to be rewritten for multiple subclasses, there is no need to write this method of the parent class, so in order to be lazy, just oneabstract method name();
Since there are abstract methods in a class, it must be an abstract class. But an abstract class can have no abstract methods
Insert picture description here
I want to mention here: it's not that it can't be instantiated, but generally it can't. If you have to, you can use an anonymous inner class to achieve it.
Insert picture description here

Second, the interface

Keywordinterface,achieve:implements
Insert picture description here
Why use an interface? The reason is: when we define a class, when we don't need member attributes, we only need methods. For example: we want to define an unlocking class, we only want unlocking and locking methods and can be bu, no attributes are needed. For convenience, it is specifically defined as an interface.
Insert picture description here
Insert picture description here

Abstract classes and interfaces:

Insert picture description here
Here is an example:

//接口-锁-只有上锁和解锁功能
public interface Lock {
    int i = 10;         //接口中只有静态常量,public static final类型,可以不写
    void lockUp();      //接口里面的方法是public abstract类型,可以不写
    void lockDown();
}
//抽象类-门-只有关门和开门
public abstract class Door {
    public abstract void open();
    public abstract void close();
}
//类-安全门-有前面两个功能
public class SafeDoor extends Door implements Lock {
    @Override
    public void open() {
        System.out.println("推一下,门开了");
    }

    @Override
    public void close() {
        System.out.println("拉一下,门关了");
    }

    @Override
    public void lockUp() {
        System.out.println("钥匙扭一扭,锁开了");
    }

    @Override
    public void lockDown() {
        System.out.println("钥匙扭一扭,锁关了");
    }
}
//类-户主-实现正常进出门和开关门
public class Owner {
    private String name;
    private SafeDoor safeDoor = new SafeDoor();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void getIn(){
        System.out.println(this.name+"来到门前,掏出钥匙");
        safeDoor.lockUp();
        safeDoor.open();
        System.out.println("进入房间");
    }

    public void getOut(){
        System.out.println("走出房间");
        safeDoor.close();
        System.out.println("门已经关上");
        safeDoor.lockDown();
        System.out.println("门已经上锁");
    }
}
//测试类
public class TestOwner {
    public static void main(String[] args) {
        Owner owner = new Owner();
        owner.setName("刘德华");
        owner.getIn();
        owner.getOut();
    }
}

The results show that:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43288259/article/details/112915583