Tuesday, May 2, 2023

Static, final, this, super keywords in apex

 static

This keyword defines a method/variable that is only initialized once and is associated with an (outer) class, and initialization code. We can call static variables/methods by class name directly. No need of creating an instance of a class.

Static variables are variables that belong to an overall class, not a particular object of a class. Think of a static variable to be like a global variable – its value is shared across your entire org. Any particular object’s properties or values are completely irrelevant when using static.

Static methods, similarly, are methods that act globally and not in the context of a particular object of a class. Being global, static methods only have access to their provided inputs and other static (global) variables.

Example

public class OuterClass {

	// Associated with instance
	public static final Integer MY_INT;
	
	// Initialization code
	static {
	MY_INT = 10;
	}
	
}

final

This keyword is used to define constants and methods that can’t be overridden.

Example

public class myCls {
    static final Integer INT_CONST;
}

this

This keyword represents the current instance of a class, in constructor chaining.

Example

public class Foo {
	
	public Foo(String s) {/* … */}
	
	public foo() {
	
	this('memes repeat'); }
	
}

super

This keyword invokes a constructor on a superclass.

Example

public class AnotherChildClass extends InnerClass {
	AnotherChildClass(String s) {
		super();
		// different constructor, no args
	}
}

return

This keyword returns a value from a method.

Example

public Integer sum() {
    return int_var;
}

transient

This keyword declares instance variables that cannot be saved, and should not be transmitted as part of the view state, in Visualforce controllers and extensions.

Example

transient integer currentValue;

null

This keyword defines a null constant that can be assigned to any variable.

Example

Boolean b = null;

Like other programming languages, there are many other keywords in Apex programming language. We will see those in other posts.