Why some classes cannot be constructed?

when I started learn Apex, I was confused, because I cannot create date instance like:

Date date = new Date();

I had to use static method

Date date = Date.newIstance(...);

So, why i must use static method and cannot use constructor?

Salesforce Asked by Andrii Pytel on December 27, 2020

1 Answers

One Answer

The new syntax is used for classes that have constructors. The keyword is the means by which you call a constructor for the class, but not all classes necessarily have constructors. Some classes are static or only have static methods. A common example of a class like that in Apex development are Lightning component controllers which typically only have static, @AuraEnabled methods and no constructors.

If I had to guess, the reason for not using a Date constructor is because Dates would have several, similar constructor method signatures. Among the methods that return new Dates there are:

  • newInstance - which takes 3 Integers
  • parse - which takes a String
  • valueOf - which takes a String or an Object, and because Object is the root type of other primitive Objects in Apex, it can be a number of things including another Date or DateTime.

Expressing those methods as constructors would leave you with the following signatures:

Date(Integer, Integer, Integer)

You end up with overlap in the latter three signatures because they all accept the same type of argument (in Apex, String is an Object). Also, the intent of a method like parse is different than the intent of a constructor. parse can take a variety of strings and do its best to parse them into a Date. With valueOf, you had best have a string that can convert cleanly to a Date or you may run into trouble.

If you're new to object oriented (OO) programming I would suggest reading over the Classes, Objects, and Interfaces documentation for Apex which talks about constructors, the static keyword, objects, and classes. For general information on object oriented programming StackOverflow has good Q&As that are more general for OO languages.

Answered by nbrown on December 27, 2020

Add your own answers!

Related Questions

How to get data from dataevents using REST API

1  Asked on January 28, 2021 by user87438


Scroll down is not working report

1  Asked on January 26, 2021 by dearbrother


Wave Analytics — containerId/versionId of a dataset

2  Asked on January 26, 2021 by sitansu-pradhan


Connected App packaging

0  Asked on January 25, 2021 by user85767


AMPSCRIPT: Hide HTML Form after clicking on Submit Button

1  Asked on January 25, 2021 by valarie-simmons


Field update before or after creation of an issue

0  Asked on January 23, 2021 by hermann-our


How to check multiple occurrences in the child records?

1  Asked on January 21, 2021 by mauforsalesforce


Live Agent Credit Card Question – Two Part

1  Asked on January 21, 2021 by stephanie-dorman


Ask a Question

Get help from others!

© 2022 All rights reserved.