09-Abstract classes, interfaces and the difference between the two in Java


1. Abstract class

concept

In Java, a method without a method body should be defined as an abstract method, and if there is an abstract method in a class, the class must be defined as an abstract class.

Characteristics of abstract classes

  • Abstract classes and abstract methods must be usedabstractKeyword modification
  • Abstract class format:

abstract class class name {}

  • Abstract method format:

public abstract void method name ();

  • Abstract classes do not necessarily have abstract methods, classes with abstract methods must be abstract classes
  • The abstract class cannot be instantiated, but there can be a construction method in the abstract class, the purpose is to initialize when the subclass accesses the parent class data
  • Abstract classes cannot be instantiated directly, they are instantiated by concrete subclasses in a polymorphic manner.
  • Subclass of abstract class
    • Either an abstract class
    • Either you must override all abstract methods in the abstract class

Example: Simple definition of abstract class

//抽象类的定义
public abstract class Animals {
    
    
    String name;
    int age;
    //共性功能定义为抽象的,抽象类只需给出共性的声明即可
    // 具体的实现细节由子类根据自身的差异性,具体去重写
    public abstract void eat();
    public abstract void sleep();
    public void show(){
    
    
        System.out.println("抽象类内可以有非抽象方法");
    }
}
//子类继承该抽象类,必须重写抽象类中的抽象方法
public class Cat extends Animals {
    
    
    //抽象方法的重写,由子类依据自身特性具体实现
    @Override
    public void eat() {
    
    
        System.out.println("猫吃鱼");
    }

    @Override
    public void sleep() {
    
    
        System.out.println("猫睡沙发");

    }
    
}
public class Dog extends  Animals {
    
    
    @Override
    public void eat() {
    
    
        System.out.println("狗吃骨头");
    }

    @Override
    public void sleep() {
    
    
        System.out.println("狗睡地上");

    }
}

Member characteristics of abstract classes

  • Member variable: either variable or constant
  • Construction method: Yes, used for the initialization of the subclass to access the parent class data.
  • Member method: It can be abstract or non-abstract.

note

The member method characteristics of abstract classes:

  • Abstract methods force subclasses to do things
  • Non-abstract method subclass inheritance, improve code reusability

Example: how to instantiate an abstract class

public class Mytest {
    
    
    public static void main(String[] args) {
    
    
        //采用多态的形式创建父类引用,间接实例化父类
        Fu fu=new Zi();
        //多态中成员变量的访问特点:编译看左,运行看左
        System.out.println(fu.num);
        //多态中成员方法的访问特点:编译看左,运行看右
        fu.show();
        //向下转型,将父类引用强制转化成子类引用
        Zi zi=(Zi)fu;
        System.out.println(zi.num);
        zi.show();
    }
}
 abstract class Fu{
    
    
    int num=10;
    //抽象类不能直接实例化,但是有构造方法
    public Fu(){
    
    
        System.out.println("父类构造方法执行");
    }
    public abstract void show();

}
class Zi extends Fu{
    
    
    int num=20;
    public Zi(){
    
    
        System.out.println("子类构造方法执行");
    }

    @Override
    public void show() {
    
    
        System.out.println("子类show方法执行");
    }
}

operation result:
Insert picture description here

Thinking

  • If a class has no abstract methods, can it be defined as an abstract class?

    Yes, the outside world cannot create such objects, which is equivalent to the construction method of privatized classes.

  • What keywords can't abstract coexist with ?

    • final: contradictory, abstract mandatory subclass must be rewritten, final does not allow subclass rewriting
    • private: contradictory, abstract forces subclasses to be rewritten, private subclasses cannot be inherited and cannot be rewritten
    • static: static method belongs to the class, so it does not participate in rewriting, meaningless

Exercise

Requirements: If we need to design the employee (Employee) class when developing a system, the employee contains 3 attributes: name, job number and salary (salary).
Manager is also an employee. In addition to the attributes of the employee, there is also a bonus attribute. Then define the method of work.
Please use the idea of ​​inheritance to design the employee class and manager class.

//定义一个抽象类,将员工和经理的共性抽取出来,并声明一个抽象方法。
public abstract class person {
    
    
    public String name;
    public int num;
    public double salary;
    public abstract void workshow();
}

//员工类继承该抽象类,并依据自身的特性,实现抽象类中的抽象方法
public  class Employee extends person {
    
    
    @Override
    public void workshow() {
    
    
        System.out.println("员工一周工作七天");
    }
}
//经理继承该抽象类,并重写抽象方法。声明额外属性bouns
public class Manager extends person{
    
    
    public double bouns;
    @Override
    public void workshow() {
    
    
        System.out.println("经理一周工作5天");
    }
}
//测试类
public class Mytest {
    
    
    public static void main(String[] args) {
    
    
        //使用多态的方式,创建对象
        person p=new Employee();
        p.name="小明";
        p.num=224075;
        p.salary=3500;
        System.out.println("员工名字:"+p.name+";职工号:"+p.num+";月薪:"+p.salary);
        //多态中成员方法的访问特点:编译看左,运行看右
        p.workshow();
        System.out.println("====================================================");
        person p1=new Manager();
        p1.name="赵建国";
        p1.num=1;
        p1.salary=7500;
        //向下转型,才能调用子类中的特有属性
        ((Manager) p1).bouns=800;
        System.out.println("经理名字:" + p1.name + ";职工号:" + p1.num + ";月薪:" + p1.salary+";奖金:"+((Manager) p1).bouns);
        p1.workshow();
    }
}

operation result:
Insert picture description here

2. Interface

concept

In order to reflect the extensibility of things, Java provides interfaces to define these additional functions, and does not give specific implementations. It is enough to hand over these additional functions to some specific objects.

Features of the interface

  • Keyword for interface interface format:

interface interface name{}

  • The class implementation interface uses the implements format:

class class name implements interface name {}

  • The interface cannot be instantiated directly, it needs to be instantiated in a polymorphic manner
  • Interface subclass
    • It can be an abstract class, but it has little meaning
    • It can be a concrete class. To rewrite all abstract methods in the interface.

Characteristics of interface members

  • Member variables: can only be constants and static. Default modifier: public static final (it is recommended to give it manually)
  • Construction method: the interface has no construction method
  • Member method: only abstract method, default modifier: public abstract (it is recommended to give it manually)

Example: Simple definition and implementation of interface

//定义一个接口,接口中定义的都是一些扩展功能,哪类事物需要具备该扩展功能,就需要实现该接口。
public interface Myinterface {
    
    
    public static final int num=1000;//默认修饰符:public static final
    public abstract  void calc();//默认修饰符:public abstract
}
//子类实现父接口,必须重写接口中的所有抽象方法
public class person implements Myinterface {
    
    
    @Override
    public void calc() {
    
    
        System.out.println("人会算数");
    }
    public void love(){
    
    
        System.out.println("人有情感");
    }
}
public class dog implements Myinterface {
    
    
    @Override
    public void calc() {
    
    
        System.out.println("狗经过后天训练,也会算数");
    }
    public void watchdoor(){
    
    
        System.out.println("狗会看家");
    }
}
//使用多态的形式,创建对象。
public class mytest {
    
    
    public static void main(String[] args) {
    
    
        //接口不能创建对象,子类和接口之间是实现关系,可以叫父接口,子类
        //采用多态的形式
        Myinterface myinterface=new person();
        myinterface.calc();
        System.out.println(myinterface.num);
        //想要调用子类中独有的方法,需向下转型
        person p=(person)myinterface;
        p.love();
        System.out.println(p.num);
        System.out.println("=====================================");
        Myinterface myinterface1 = new dog();
        myinterface1.calc();
        System.out.println(myinterface1.num);
        dog d=(dog)myinterface1;
        d.watchdoor();
        System.out.println(d.num);

    }
}

3. The difference between abstract class and interface

  • Membership difference

    • Abstract class

      • Member variable: it can be a variable or a constant
      • Construction method: Yes
      • Member method: it can be abstract or non-abstract
    • interface

      • Member variables: must be public static constants modified by default public static final
      • Member methods: only abstract methods can be defined after JDK1.8. Default modification methods can be defined. Specific implementation of functions can be given. Subclasses can be inherited and used. After JDK1.8, static methods can also be defined in interfaces.
  • Relationship difference

    • Class and class

      • Inheritance, single inheritance, multiple inheritance
    • Class and interface

      • Realization, single realization, multiple realization
    • Interface and interface

      • Inheritance, single inheritance, multiple inheritance
  • Design concept difference

    • Abstract class, inherited reflects the relationship of "is a", and what is defined in abstract class is the common function of the inheritance system
    • The interface is implemented to reflect the relationship of "like a", and the interface defines the extension function of the inheritance system.

Guess you like

Origin blog.csdn.net/m0_46988935/article/details/110522946