Abstract Class In Apex

An abstract class is a class that contains at least one abstract method, which is a method without a body (implementation). An abstract class cannot be instantiated on its own, but it can be inherited by other classes. When a class extends an abstract class, it must provide an implementation for all the abstract methods that are defined in the abstract class, otherwise, it should also be declared as an abstract class. There are a few other important points to consider when working with abstract classes:

Abstract classes can have both abstract and non-abstract methods: In addition to abstract methods, abstract classes can also have non-abstract methods with an implementation. These methods can be called from the inheriting classes without any modifications.

Abstract classes can have constructors: Abstract classes can have constructors that are called when an instance of the inheriting class is created. However, the constructor of an abstract class cannot be called directly, but only through the constructor of the inheriting class.

Abstract classes can implement interfaces: An abstract class can implement one or more interfaces. In this case, the abstract class must provide an implementation for all the methods defined in the interface(s) it implements.

Abstract classes can provide default implementations for methods: Since Java 8, abstract classes can provide default implementations for methods. These methods can be overridden by the inheriting classes, but they provide a default behaviour that can be used if no overriding is needed.

Abstract classes can have final methods: Abstract classes can also have final methods that cannot be overridden by the inheriting classes. This can be useful if the abstract class wants to enforce a specific behaviour that should not be changed by the inheriting classes.

    public abstract class Shape {
    public Integer numberOfSides { get; set; }
    public String color { get; set; }
    public abstract Decimal calculateArea();
    public abstract Decimal calculatePerimeter();
    public void setColor(String c) {
        color = c;
    }
}
      

In this example, the Shape class has a non-abstract method called setColor(), which sets the color property of the Shape object. This method has an implementation in the Shape class, so it does not need to be overridden by the subclasses. Note that a subclass can still override the setColor() method if it wants to provide a different implementation. However, since the setColor() method is not declared as abstract, it is not required to provide an implementation in the subclass.

Article Information