Talk about java abstract classes and interfaces in detail

Abstract classes and interfaces

abstract class

Abstract class: A class is abstract if there is not enough information in it to describe an object

Getting Started with Abstract Classes

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-ecnu0Hm1-1668610029926) (C:\Users\dongguozhen\AppData\Roaming\Typora\typora-user-images\ image-20221115082319474.png)]

  • The rectangle, triangle, and circle classes are all graphics classes, so the relationship with Shape should be extends
  • Although there is also a draw method in the Shape class, Shape is not a specific graphic, so there is no method for the internal drawing method to be implemented.
  • The Shape class has no way to describe a specific graphic, so the draw method inside has no way to realize it, so you can set Shape as an abstract class modified by abstract, and set draw as an abstract method modified by abstract.

Notice:

An abstract class is also a class, which can contain ordinary methods and properties, and even constructors

When there is an abstract method in the abstract class, the abstract method must be rewritten in the subclass.

Code

Interpretation:

  • Animal is an animal class, and each Animal has a method called, but Animal is not a specific animal, so the bark() method in the Animal class cannot be implemented specifically.
  • Dog is a dog class. First of all, a dog is an animal, and it is an inheritance relationship with Animal. A dog is a specific animal, and then the dog class can implement the bark method. What is the specific name?
  • Cat is a cat class. First of all, a cat is an animal, and it is an inheritance relationship with Animal. A cat is a specific animal, and then the cat class can also implement the bark method. What is the specific name?

Abstract class syntax:

If a class is modified by abstract, it is called an abstract class, and the method modified by abstract in the abstract class is called an abstract method, and the abstract method does not need to provide a specific implementation body.

package ClassANDObject.Abstract.Abstract01;

abstract class Animal {
    
    
    //注意:抽象类也是类,内部可以包含普通方法和属性,甚至构造方法
    private String name;

    public Animal(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }

    public abstract void bark();//抽象类可以不写方法的实现
}
class Dog extends Animal{
    
    
    public Dog(String name) {
    
    
        super(name);
    }

    @Override
    public void bark() {
    
    //重写了抽象类
        System.out.println("小狗 "+getName()+" 正在汪汪叫");
    }
}
class Cat extends Animal{
    
    
    public Cat(String name) {
    
    
        super(name);
    }

    @Override
    public void bark() {
    
    //重写了抽象类
        System.out.println("小猫 "+getName()+" 正在咪咪叫");
    }
}
public class test{
    
    

    public static void show(Animal animal){
    
    //用多态思想去调用
        animal.bark();
    }
    public static void main(String[] args) {
    
    
       // Animal animal = new Animal();  抽象类不能直接实例化对象 因为类是一个抽象的类。
        Dog dog = new Dog("大黄");
        Cat cat = new Cat("小花");
        //直接调用
        /*dog.bark();
        cat.bark();*/
        
        Animal[] animal = {
    
    dog,cat};//用多态思想去调用
        for (Animal a:animal) {
    
    
            a.bark();
        }

        show(dog);
        show(cat);
    }
}

Details of the use of abstract classes
  • The abstract class does not need to write a specific implementation, but the method should be modified with abstract -> abstract method

  • Abstract classes cannot instantiate objects directly because the class is an abstract class.

  • Animal animal = new Animal();
    //报错
    java: ClassANDObject.Abstract.Abstract01.Animal是抽象的; 无法实例化
    
  • An abstract method that cannot be private must be modified with abstract, and private cannot modify a method at the same time.

  • When an ordinary class inherits an abstract class, the abstract method in the abstract class must be overridden

  • Abstract methods cannot be modified by final static, because subclasses will eventually rewrite abstract methods to achieve concrete things.

  • The greatest significance of the existence of abstract classes is to be inherited

  • The abstract class must be inherited, and after inheritance, the subclass must rewrite the abstract method in the parent class, otherwise the subclass is also an abstract class and must be modified with abstract.

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

  • This class must be abstract as long as it contains abstract methods

  • Abstract methods must be rewritten, so they must meet the rules of heavy methods

  • Abstract classes do not necessarily contain abstract methods

  • Abstract classes can have constructors for subclasses to initialize member variables of parent classes

  • The value of the abstract class lies in the design, after the designer has designed it, let the subclass inherit and implement the abstract class

The difference between abstract class and ordinary class

Abstract classes cannot be instantiated Ordinary classes can

Abstract classes can contain non-abstract methods and abstract methods, but ordinary classes can only contain non-abstract methods

abstract class summary

The abstract class itself cannot be instantiated. If you want to use it, you can only create a subclass of the abstract class. Then let the subclass override the abstract method in the abstract class

interface

The concept of interface

insert image description here

The interface is the public standard of behavior. When everyone implements it, as long as it conforms to the standard, it can be used universally. In Java, an interface can be seen as: a public specification of multiple classes, which is a reference data type.

Interface: formulating a standard is a specification of behavior

Interface Quick Start
interface IShape{
    
    
    void draw();//接口里面指定一个标准 行为的一种规范
    public static void func(){
    
    
        System.out.println("这是一个接口里面静态的方法");
    }
}
class Rect implements IShape{
    
      //这个类和接口的关系是要执行接口的标准  使用关键字 implements

    @Override
    public void draw() {
    
    //实现了接口里面的方法,执行接口里面的标准
        System.out.println("画矩形");
    }
    public void info(){
    
    
        System.out.println("这是Rect里面的特有的方法");
    }
}
class Flower implements IShape{
    
    

    @Override
    public void draw() {
    
    
        System.out.println("❀!");
    }
    public void info(){
    
    
        System.out.println("这是Flower里面的特有的方法");
    }
}
public class test1 {
    
    
    public static void show(IShape iShape){
    
      //向上转型 可以把接口看做一个父类
        iShape.draw();
    }
    public static void show1(IShape iShape){
    
      //向下转型,调用特有的方法
        if(iShape instanceof Rect){
    
    
           Rect rect = (Rect) iShape;
           rect.info();
        }else if(iShape instanceof Flower){
    
    
            ((Flower) iShape).info();
        }
    }
    public static void main(String[] args) {
    
    
       /* Rect rect = new Rect();
        Flower flower = new Flower();*/

        IShape iShape = new Rect();//向上转型
        IShape iShape1 = new Flower();//向上转型
        show(iShape);
        show(iShape1);

        //如果要调用Flower里面特有的方法,需要进行向下转型
        show1(iShape);
        show1(iShape1);

        //如果要调用接口里面静态的方法,那么直接通过接口名来调用
        IShape.func();
    }
}

  1. Interfaces are defined using the keyword interface
  2. interface cannot be instantiated
  3. The members in the interface default to public static final static constants
  4. The methods in the interface cannot have specific implementations, only abstract methods, but starting from jdk8, you can write a default modified method, and then you can have specific implementations
  5. The abstract method of the interface is modified by public abstract by default.
  6. There is no constructor in the interface
  7. The interface needs to be implemented by the class. Use the keyword implements. The method in the interface is an abstract method by default. All the abstract methods of the interface must be rewritten in the class that implements the interface.
  8. There can be static modified methods in the interface

The essence of interface is the specification and abstraction of behavior

use of interface

The interface cannot be used directly, there must be an implementation class to implement all the abstract methods defined in the interface

The relationship between classes and classes is extends, then the relationship between classes and interfaces is implements

public interface USB {
    
    
   //定义了两个规范
   void open();
   void stop();
}
public class Monse implements USB{
    
     //实现了接口的规范

   @Override
   public void open() {
    
    
       System.out.println("打开鼠标");
   }

   @Override
   public void stop() {
    
    
       System.out.println("关闭鼠标");
   }
   public void click(){
    
    
       System.out.println("点击鼠标");
   }
}
public class KeyBoard implements USB{
    
     //实现了接口的规范

   @Override
   public void open() {
    
    
       System.out.println("打开键盘");
   }

   @Override
   public void stop() {
    
    
       System.out.println("关闭键盘");
   }
   public void click(){
    
    
       System.out.println("使用键盘");
   }
}
public class Computer {
    
    
   //站在我们这个方法的角度,我们不关心usb到底引用那个对象,只要实现了接口里面的规范就可以了

   //发生了多态
   public void usbdiv(USB usb){
    
     //发生了向上转型
       usb.open();
       if(usb instanceof Monse){
    
     //向下转型    调用特有的方法,即接口没有定义的规范
           Monse monse = (Monse)usb;
           monse.click();
       }else if(usb instanceof KeyBoard){
    
    //向下转型
           ((KeyBoard) usb).click();
       }
       usb.stop();
   }
}
public class test {
    
    
   public static void main(String[] args) {
    
    

       Monse monse = new Monse();
       Computer computer = new Computer();
       KeyBoard keyBoard = new KeyBoard();
       computer.usbdiv(monse);
       computer.usbdiv(keyBoard);
   }
}

An abstract class is abstracting a thing, an interface is abstracting a behavior, and setting standards

Characteristics of the interface

1: An interface is a reference type, but an object of an interface cannot be directly new

interface USB{
    
    
    
}
public class A{
    
    
    public static void main(String[] args){
    
    
        USB usb = new USB(); //直接报错
    }
}

2: Every method in the interface is an abstract method modified by public, that is, the method in the interface will be written as public abstract by the hermit, and an error will be reported if other combinations are written

3: The methods in the interface cannot be implemented by the interface, but can only be implemented by the class that implements the interface. If you want to implement it, you must write default

4: When rewriting the method of the interface, the default access modification permission cannot be written

5: The interface contains variables, but the variables in the interface will be written as public static final variables by hermits

6: There cannot be static code blocks and construction methods in the interface

7: Although the interface is not a class, the suffix format of the bytecode file after the interface is compiled is also .class

8: If the class does not implement all the abstract methods in the interface, the class must be set as an abstract class

implement multiple interfaces

In Java, there is single inheritance between classes and classes. A class can only have one parent class, that is, multiple inheritance is not supported in Java, but a class can implement multiple interfaces. A group of animals is represented by a class below.

public class Animal {
    
     //父类
    private String name;

    public Animal(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }
}
public interface Flying {
    
     //飞的接口
    void fly();
}
public interface RUNing {
    
    //跑的接口
     void run();
}
public interface Swim {
    
     //游泳的接口
    void swimming();
}
public class Dog extends Animal implements RUNing {
    
     //子类,并实现了RUNing这个接口的规范
    public Dog(String name) {
    
    
        super(name);
    }

    @Override
    public void run() {
    
    
        System.out.println(getName()+"正在用狗腿跑");
    }
}
public class Duck extends Animal implements RUNing,Swim, Flying {
    
    
    //鸭子这个动物具备多种行为  实现了多个接口的规范
    //既要实现多个接口
    //这个类继承了一个父类,同时实现了多个接口
    //鸭子也是一种动物, 既能跑, 也能游, 还能飞

    public Duck(String name) {
    
    
        super(name);
    }

    @Override
    public void fly() {
    
    
        System.out.println("鸭子"+getName()+"正在飞");
    }

    @Override
    public void run() {
    
    
        System.out.println("鸭子"+getName()+"正在跑");
    }

    @Override
    public void swimming() {
    
    
        System.out.println("鸭子"+getName()+"正在游泳");
    }
}
public class Fish extends Animal implements Swim{
    
      //子类,并实现了Swim这个接口的规范
    public Fish(String name) {
    
    
        super(name);
    }

    @Override
    public void swimming() {
    
    
        System.out.println(getName()+"正在游泳");
    }
}
public class Frog extends Animal implements Swim, RUNing {
    
     //同时实现多个接口的规范
    //青蛙这个动物具备多种行为
    //既要实现多个接口
    //这个类继承了一个父类,同时实现了多个接口
    //青蛙是一个动物,能游泳还能跑
    public Frog(String name) {
    
    
        super(name);
    }

    @Override
    public void run() {
    
    
        System.out.println("青蛙"+getName()+"正在跑");
    }

    @Override
    public void swimming() {
    
    
        System.out.println("青蛙"+getName()+"正在游泳");
    }
}
public class MAIN {
    
    

    //在我们这个角度,我们不关心他到底是那种动物,只能是实现了相应的接口,就行
    //可以不关心具体的类型,只需要关心具体的能力、行为
    public static void run(RUNing runing) {
    
    
        runing.run();
    }
    public static void Flying(Flying flying) {
    
    
        flying.fly();
    }
    public static void swim(Swim swim) {
    
    
        swim.swimming();
    }
    
    public static void main(String[] args) {
    
    
        Dog dog = new Dog("旺财");
        run(dog);
        Duck duck = new Duck("唐老鸭");
        Flying(duck);
        run(duck);
        swim(duck);
        Fish fish = new Fish("7秒");
        swim(fish);
        Frog frog = new Frog("呱呱");
        run(frog);
        swim(frog);
    }
}

Note: When a class implements multiple interfaces, the abstract method in each interface must be implemented, otherwise the class must be set as an abstract class.

inheritance between interfaces

In Java, there is single inheritance between classes and classes, a class can implement multiple interfaces, and interfaces can have multiple inheritance. That is: using interfaces can achieve the purpose of multiple inheritance. An interface can inherit an interface to achieve the effect of reuse. Use the extends keyword.

interface a{
    
    
    void funa();
}
interface b{
    
    
    void funb();
}
interface c extends a,b{
    
       //可以看做接口的扩展
    void func();
}
class test implements c{
    
       //这个类必须要实现继承来的所有标准,即方法。

    @Override
    public void funa() {
    
    
        
    }

    @Override
    public void funb() {
    
    

    }

    @Override
    public void func() {
    
    

    }
}

Notice:

Inheritance between interfaces is equivalent to merging multiple interfaces together.

Guess you like

Origin blog.csdn.net/qq_63525426/article/details/127895200