Extends and Implements
Extends and Implements
extends
Defintion:
"Extends" is used to create a class hierarchy where one class (subclass) inherits
properties and methods from another class (superclass). It establishes an "is-a"
relationship, meaning a subclass is a type of the superclass.
Use "extends" when you want to create a new class that builds upon or specializes an
existing class. This allows you to reuse code and inherit behavior from the superclass.
In Apex, you can use the extends keyword to create a subclass that inherits properties and
methods from a superclass. Here's an example:
Example Code:
Animal Class
System.debug('Animal speaks');
Dog Class
System.debug('Dog barks');
}
Cat Class
System.debug('Cat meows');
In this example, the Dog and Cat classes extend the Animal class, which means they
inherit the speak method from the Animal class. However, each subclass can override the
method to provide its own implementation, as demonstrated with the speak method in
both Dog and Cat classes.
implements
Definition:
Use "implements" when you want to enforce a contract for method implementations
across multiple classes. It's useful when you want multiple classes to have the same
method signatures but potentially different implementations.
In Apex, you can define an interface with a set of method signatures, and then a class can
implement that interface by providing concrete implementations for those methods.
Here's an example:
Example Code:
Shape Class
void draw();
}
Circle Class
System.debug('Drawing a circle');
Rectange Class
System.debug('Drawing a rectangle');
In this example, the Circle and Rectangle classes both implement the Shape interface by
providing their own implementation of the draw method.
Note: Interface methods do not have access modifiers, they are always global.
Summary:
"extends" is used for creating class hierarchies and inheriting properties and methods,
while "implements" is used for defining interfaces and ensuring that classes provide
specific methods. Use "extends" when you want to establish an inheritance relationship,
and "implements" when you want to define a common set of methods that multiple
classes must implement.