TransWikia.com

Why some classes cannot be constructed?

Salesforce Asked by Andrii Pytel on December 27, 2020

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?

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)
Date(String)
Date(String)
Date(Object)

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!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP