Differences Between Apex Classes and Java Classes
Apex classes and Java classes work in similar ways, but there are some significant differences.
These are the major differences between Apex classes and Java classes:
-
Inner classes and interfaces can only be declared one level deep inside an outer class.
-
Static methods and variables can only be declared in a top-level class definition, not in an inner class.
-
An inner class behaves like a static Java inner class, but doesn’t require the
statickeyword. An inner class can have instance member variables like an outer class, but there is no implicit pointer to an instance of the outer class (using thethiskeyword). -
The
privateaccess modifier is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable isprivate. -
Specifying no access modifier for a method or variable and the
privateaccess modifier are synonymous. -
The
publicaccess modifier means the method or variable can be used by any Apex in this application or namespace. -
The
globalaccess modifier means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable asglobal, you must also declare the class that contains it asglobal. -
Methods and classes are final by default.
- The
virtualdefinition modifier allows extension and overrides. - The
overridekeyword must be used explicitly on methods that override base class methods.
- The
-
Methods defined in an interface have the same access modifier (
publicorglobal) as the interface. -
Exception classes must extend either exception or another user-defined exception.
- Their names must end with the word
exception. - Exception classes have four implicit constructors that are built-in, although you can add others.
- Their names must end with the word
-
Classes and interfaces can be defined in triggers and anonymous blocks, but only as local.
See Also