Tuesday 3 May 2016

Private VS Final in java

Private
Final

Possible
Example/Other comments.
Possible
Example/Other comments.
Class
N
Only private inner classes are possible.
Y
Final class cannot be inherited
Variable
Y
Private variables cannot be read outside class without being accessed by its own class method.
Y
An initialized final variable cannot be changed ever.

Uninitialized Instance final  variable
- An unitialized final variable MUST be initialized either ONLY in instance block, in which case you cannot initialize it even in constructors.
ELSE if there is no instance block, it MUST be initialized in  ALL its constructors, failing which there is compile time error.

Uninitialized static  final variable
-  I observed that there was a compile time error on declaring a final static variable without being initialized. Initializing it even in static method would not solve the error.
Constructor
Y
If you make a constructor private, you restrict the implicit/default call of super constructor and thus you restrict class being inherited and you restrict object creation of the class having private constructor. So you cannot create an object of a class with private constructor.
N
Constructors cannot be final.
Error:
Illegal modifier for the constructor in type parentClass; only public, protected & private are permitted
Method
Y
You cannot override a private method. Nor can you access a private method from outside class. You can access private method if another methof of same class calls the private method, in which case you can create object of class and call the method which in turn calls private methods.
Y
A final method cannot be overridden. Can be tested with help of upcasting.