Virtual Class in Apex
A class that extends another class inherits all the methods and properties of the extended class. In addition extending class can override the existing virtual methods by using
Check below code
override
keyword in the method definition. Overriding a virtual method allows you to provide a different implementation for an existing method. This means that the behavior of a particular method is different based on the object you're calling it. This is referred as polymorphism.- just like abstract class, it is not mandatory to override virtual methods.
- virtual and abstract classes can extends virtual class.
Check below code
Now open developer console and run below code snippet and observe the logs
Defining a child class which extends a Abstract class which is extending a virtual class
Open developer console and run below code and observe the logs
Reference:
Marker obj1, obj2;
obj1 = new Marker();
// This outputs 'MARKER: writing some text'
obj1.write();
obj2 = new BlueMarker();
// This outputs 'BLUEMARKER: writing some text using BlueMarker'
obj2.write();
// We get the price of marker
// and can call it from the BlueMarker instance.
Integer i = obj2.price();
system.debug(' price: ' + i);
Debug logs:- Abstract class can also extends virtual class
defining a abstract class which extends a virtual class
Defining a child class which extends a Abstract class which is extending a virtual class
Open developer console and run below code and observe the logs
Marker obj1, obj2, obj3;
obj1 = new Marker();
// this will output : 'MARKER: writing some text'
obj1.write();
obj2 = new ExtendController();
//below will output: 'ABSTRACTMARKER: writing text with permanent Marker.'
obj2.write();
// below code will give an error 'Abstract classes cannot be constructed: AbstractMarker'
obj3 = new AbstractMarker();
obj3.write();
Reference:
No comments:
Post a Comment