抽象类
抽象类是被声明为抽象 的类 -它可能包含也可能不包含抽象方法。抽象类不能被实例化,但是可以被子类化。抽象类可能具有静态字段和静态方法。当抽象类被子类化时,该子类通常为其父类中的所有抽象方法提供实现。但是,如果没有,则子类也必须声明为抽象。
抽象方法是一种无需实现即可声明的方法(不带花括号,后跟分号),如下所示:
abstract void sum(int a, int b);
如果以下任何一种情况适用于您的情况,请考虑使用抽象类:
Interface
接口只是对象方法的声明。这不是实现。在接口中,我们定义对象可以执行的操作。这些操作由实现接口的类定义。接口在类和外部世界之间形成契约,并且该契约在编译时由编译器强制执行。
interface Vehical { // declaration void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } class Car implements Vehical { int speed = 0; int gear = 1; // implementation void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println(" speed:" + speed + " gear:" + gear); } }
如果以下任何一种情况适用于您的情况,请考虑使用接口:
原文链接:https://blog.csdn.net/Beibnjin/article/details/113827586?utm_medium=distribute.pc_category.none-task-blog-hot-1.nonecase&depth_1-utm_source=distribute.pc_category.none-task-blog-hot-1.nonecase&request_id=