The class name in which a
static
method is declared may be used in the method invocation.
For example, if
static
method1()
is declared in
MyClass,
then
method1()
may be invoked as
MyClass.method1()
.
Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directly.
- Class methods must use an object reference.
Also, class methods cannot use the this keyword as there is no instance for this to refer to.
In Java, the keywords synchronized, transient, and volatile are classified as modifiers. These are used to modify the behavior of variables or methods in specific ways:
- synchronized: It is a method or block modifier that ensures that a method or block of code can only be accessed by one thread at a time.
This is useful for managing concurrent access to shared resources.
The synchronized
modifier identifies synchronized
methods and synchronized
statements.
Example:
public synchronized void methodName() {
// Code that is thread-safe
}
- transient: It is a variable modifier that indicates that a variable should not be serialized when the object containing it is serialized. In other words, the value of a transient variable is not persisted during serialization. The
transient
modifier identifies a variable that may not be serialized. A transient
variable may not be declared as final
or static
.
Example:
private transient int tempData; // This field will not be serialized
- volatile:It is a variable modifier used for multi-threaded programming. It indicates that a variable's value may be changed by multiple threads, ensuring that the value of the variable is always read from the main memory, not from a thread's local cache.
The volatile
modifier is used to indicate that a variable may be modified asynchronously in a multiprocessor environment.
Example:
private volatile boolean isActive; // This ensures visibility across threads
These modifiers are mainly used to manage synchronization, serialization, and visibility in multi-threaded environments.