27. What is a final modifier ? Explain other Java modifiers


A final class can’t be extended i.e. A final class may not be subclassed. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (i.e. it is a constant).

Modifier

Class

Method

Property

static

A static inner class is just an inner class associated with the class, rather than with an instance.


cannot be instantiated, are called by classname.method, can only access static

variables


Only one instance

of the variable exists.


abstract

Cannot be instantiated, must be a superclass, used whenever one or more methods are abstract.


Method is defined but contains no implementation code (implementation code is included in the subclass). If a method is abstract then the entire class must be abstract.


N/A

synchronized

N/A

Acquires a lock on the class for static methods.

Acquires a lock on the instance for non-static methods.


N/A

transient

N/A

N/A

Field should not

be serialized.


final

Class cannot be inherited


Method cannot be overridden


Makes the variable

a constant. Cannot be modified.


native

N/A

Platform dependent. No body, only signature.


N/A



Note: Be prepared for tricky questions on modifiers like, what is a “volatile”? Or what is a “const”? Etc. The reason it is tricky is that Java does have these keywords “const” and “volatile” as reserved, which means you can’t name your variables with these names but modifier “const” is not yet added in the language and the modifier “volatile” is very rarely used.

The “volatile” modifier is used on member variables that may be modified simultaneously by other threads. Since other threads cannot see local variables, there is no need to mark local variables as volatile. E.g. volatile int number; volatile private List listItems = null; etc. The modifier volatile only synchronizes the variable marked as volatile whereas “synchronized” modifier synchronizes all variables.

Java uses the final modifier to declare constants. A final variable or constant declared as “final” has a value that is immutable and cannot be modified to refer to any other objects other than one it was initialized to refer to. So the “final” modifier applies only to the value of the variable itself, and not to the object referenced by the variable. This is where the “const” modifier can come in
very useful if added to the Java language. A reference variable or a constant marked as “const” refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as “final”. The “const” modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier “final”.



1 comment:

  1. Very beautifully explained about Modifiers in Java programming. Great help for me to understand about this topic. I am very glad to read this article. Keep it up your excellent work in the same devotion.

    ReplyDelete