search
HomeJavajavaTutorialThe role and design principles of interfaces and abstract classes in Java

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.

Java 中接口和抽象类的作用和设计原则

The role and design principles of interfaces and abstract classes in Java

Interface

  • Define methods but do not provide implementations.
  • Declare a series of public constants.
  • Force the class that implements it to provide implementation of all methods.
  • Syntax: public interface InterfaceName { ... }

Abstract class

  • Definition method , can be an abstract method or a concrete method.
  • Abstract methods are not implemented and must be implemented by subclasses.
  • Fields and constructors are allowed.
  • Syntax: public abstract class AbstractClassName { ... }

Function

Interface

  • Achieve decoupling, allowing classes to focus on their own responsibilities.
  • Promote modularity and extensibility so that components can be easily interchanged and extended.
  • Define behavior contracts to force implementation classes to comply with specific specifications.

Abstract class

  • Defines a common behavior and forces subclasses to inherit it.
  • Provide partial implementation to reduce repeated code in subclasses.
  • Provide hook methods to allow subclasses to customize specific behaviors.

Design principles

Interface

  • Define only necessary behavior.
  • Method names should be clear and concise, indicating expected behavior.
  • Interfaces should be kept small and focused.

Abstract class

  • Only declares abstract methods and defines public behavior.
  • Provide concrete methods to implement common behavior.
  • Consider using abstract classes instead of interfaces when shared implementations are required.

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools