Object Creation in Apex: Best Practices | Exam Prep

Create Object from Class Definition - Apex Exam Guide

Question

The method used to create an object out of a class definition is called a:

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The correct answer is A. constructor.

In object-oriented programming, a class is a blueprint for creating objects. It defines the properties and behaviors of the objects that will be created based on it. An object is an instance of a class, and the process of creating an object from a class is called instantiation.

A constructor is a special method that is used to initialize an object when it is created. It has the same name as the class and does not have a return type. It is typically used to set the initial values of the object's properties or to perform other initialization tasks.

In Apex, a constructor is created using the same syntax as a method, but with the name of the class instead of a method name. For example, the following code defines a class with a constructor that takes two parameters and sets the values of two properties:

vbnet
public class MyClass { public Integer value1; public String value2; public MyClass(Integer val1, String val2) { value1 = val1; value2 = val2; } }

To create an object of this class, you would use the new keyword and pass in the constructor parameters:

vbnet
MyClass obj = new MyClass(42, 'hello');

This would create a new object of the MyClass class and set the value of the value1 property to 42 and the value of the value2 property to 'hello'.

So, in summary, the method used to create an object out of a class definition is called a constructor.