- Static variables information need to access with static get() methods.
- Non static variables information need to access with non static get() methods.
class Test
{
private int a ;
public int getA()
{
return this.a ;
}
}
public class Access
{
public static void main(String args[ ])
{
Test obj = new Test();
// System.out.println("a value : " + obj.a); -> Error : private access
System.out.println("a value : " + obj.getA());
}
}
Following diagram explains where to access private modifier in Java:
private class Program
{
/* logic */
}
Compiler throws error when we compile above code
Why a class cannot be private?
- A class represents object.
- Private members can be accessed with in the class (by same object itself).
- If class is private, the entire object is not visible to outside world for communication. Hence it is useless of defining a class using private modifier.
Private constructor: If constructor is private, we cannot instantiate the class from other classes.
class First
{
First()
{
System.out.println("First class object created");
}
}
class Second
{
public static void main(String args[ ])
{
new First();
}
}
Trying to create object with private constructor:
class First
{
private First()
{
System.out.println("First class object created");
}
}
class Second
{
public static void main(String args[ ])
{
new First(); //Error : Cannot create object.
}
}
- We cannot instantiate a class in java without constructor call. In the definition of Singleton and Factory class design patterns we use private constructor.
- We request the object using static method.
- Once we get the object, we access the non static functionality using that object.
class First
{
private First()
{
System.out.println("First class object created");
}
void fun()
{
System.out.println("First class functionality");
}
static First getObject()
{
return new First();
}
}
class Second
{
public static void main(String args[ ])
{
First obj = First.getObject(); // request for object
obj.fun(); // access the functionality
}
}
Sample code:
class Sample
{
static void m1(){
System.out.println("Sample class static method");
}
void m2(){
System.out.println("Sample calss non static method");
}
private Sample(){
System.out.println("Sample object created...");
}
static Sample getObject(){
Sample obj = new Sample();
return obj;
}
}
public class Test
{
public static void main(String args[ ])
{
Sample.m1();
// Sample addr = new Sample(); // Error : cannot create object directly.
Sample addr = Sample.getObject(); // collect object address on request
addr.m2();
}
}