The role of interfaces and abstract classes: Interface: Defines necessary behaviors and forces implementation classes to comply with specific specifications. Abstract class: Defines common behavior, forces subclasses to inherit it, provides partial implementation, and allows subclasses to customize specific behaviors. Design Principles: Interface: Keep it small and focused, defining the necessary behavior. Abstract class: declares only abstract methods and provides concrete methods to achieve common behavior. Example: In the shape class hierarchy, the Shape interface defines the behavior of obtaining the area, the AbstractShape abstract class provides the width and height fields, and the Rectangle and Circle classes inherit the abstract class and provide the area calculation method for a specific shape.
The role and design principles of interfaces and abstract classes in Java
Interface
public interface InterfaceName { ... }
Abstract class
public abstract class AbstractClassName { ... }
Function
Interface
Abstract class
Design principles
Interface
Abstract class
Practical case
Consider a simple shape class hierarchy:
**`
java
interface Shape {
double getArea();
}
abstract class AbstractShape implements Shape {
protected double width; protected double height; public AbstractShape(double width, double height) { this.width = width; this.height = height; } public double getWidth() { return width; } public double getHeight() { return height; }
}
class Rectangle extends AbstractShape {
public Rectangle(double width, double height) { super(width, height); } @Override public double getArea() { return width * height; }
}
class Circle extends AbstractShape {
public Circle(double radius) { super(radius, radius); } @Override public double getArea() { return Math.PI * width * width; }
}
public class Main {
public static void main(String[] args) { Shape rectangle = new Rectangle(4, 5); Shape circle = new Circle(3); System.out.println("Rectangle area: " + rectangle.getArea()); System.out.println("Circle area: " + circle.getArea()); }
}
在这个例子中: * `Shape` 接口定义了一个通用行为:获取形状面积。 * `AbstractShape` 抽象类提供了通用行为的通用实现,例如宽度和高度字段。 * `Rectangle` 和 `Circle` 类通过继承 `AbstractShape` 类来扩展形状类层次结构,并提供特定形状的具体方法来计算面积。
The above is the detailed content of The role and design principles of interfaces and abstract classes in Java. For more information, please follow other related articles on the PHP Chinese website!