Sobes.tech
Junior — Middle

Can you declare an Entity as an abstract class in object-oriented programming?

sobes.tech AI

Answer from AI

Yes, in Java, you can declare a class as abstract using the abstract keyword. An abstract class cannot be instantiated directly and can contain both abstract methods (without implementation) and regular methods with implementation.

If you have an entity that you want to make a base for other classes, and at the same time want it to define a common interface or behavior but not be instantiated itself, declaring it as an abstract class is the correct approach.

Example:

public abstract class Entity {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    // Abstract method that subclasses must implement
    public abstract void save();
}

Subclasses will inherit from Entity and implement the save() method.

Can you declare an Entity as an abstract class in… - sobes.tech