How Apex Classes differ from Java Classes (Few key points)
Apex classes and Java classes work quite similar, but there are some differences.
Access Modifiers in Apex
- The default access modifier in Apex is private, while in Java it is default.
- public in Java is not same as public in apex. public in Apex means the method or variable can be used by any Apex in this application or namespace. if you want to make something public like it is in Java, you need to use the global.
- If you declare a method or variable as global, you must also declare the class that contains it as global.
Static in Apex
- Apex classes can’t be static.
- 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 static keyword.
- A class static variable Or static method can’t be accessed through an instance of that class.
Inheritance in Apex
Methods and classes are final by default. The virtual definition modifier allows extension and overrides.
public virtual class Marker {
public virtual void write() {
System.debug('Writing some text.');
}
public virtual Double discount() {
return .05;
}
}
The override keyword must be used explicitly on methods that override base class methods.
// Extension for the Marker class
public class YellowMarker extends Marker {
public override void write() {
System.debug('Writing some text using the yellow marker.');
}
}
Interface methods have no modifiers—they are always global.
public interface Order {
// All other functionality excludedDouble discount();
}
Exception in Apex
- To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the word Exception, such as “MyException” .
public class MyException extends Exception {}
- Exception classes have four implicit constructors that are built-in.
new MyException();
new MyException('This is bad');
new MyException(e);
new MyException('This is bad', e);
Source:
QA Engineer / Salesforce testing
3 年Hi, could u pls suggest a solution for how to run the apex script in java? For example, if I have apex code that creating an account object and I want to copy this one and run it in java function?
Recruiter at US Software company
5 年nice one.