How class declared as private be accessed outside of its package in Java?
Classes in Java
According to the access, modifier’s the four classes are public, private, protected and the default class. there are different ways to declare and get access to these classes. Methods, constructors, and variables of these classes have different access control. For example using the public access modifier, one can access any public class belonging to the java. But it has to get inherited from that particular package. In a similar way, the protected, public and default class has some limitations of accessing the various classes in java.
Private access modifier – Private
In this class, the methods, constructors, and variables are declared private and do not share any access with the other classes of a different package. Moreover, the private access modifier has the most restrictive access level. The variables from the private class can be declared outside the class only if the public methods are present in the class.
Two ways to make the private variable accessible outside of its package:-
- getFormat(): It is a public method which returns the value.
- setFormat(): It sets the value.
It can also be called a reflection method, which helps in invoking the private class members. The set method will help in making that member accessible in the class.
The members within the private class is restricted and can only be accessed within the same class. Moreover, the attributes are made to hide from the world. In order to access it to some different package, get methods are used. A private attribute can be invoked and used in some other class by using the get method. The get method will invoke the private member with its value defined and the value cannot be changed. Thus by making a public accessor one can accesss the private attribute outside its package in java.