Within the topic of OOP, we must distinguish the following:
ENCAPSULATION
Public = > All the methods and properties that are declared in this way are accessible from any point, that is, inside and outside the class that defines them.
Private = > All the elements that are declared in this way are only accessible within the scope of the class that delcaró
Protected = > All the elements that are declared in this way are accessible within the class that declared them, as well as only those classes that inherit from the one that contains them.
The issue of applying encapsulation must be preceded by understanding the level of access that each method and / or property that you need to declare must have
EXAMPLE WITH PROTECTED
In this fragment of code I am indicating that both the property that will store the connection, and the method that will allow me to connect to the database manager, then any class that does not inherit from Server
will not be able to access to the aforementioned
public class Server
{
protected String conexion;
protected Server(String server)
{
server = server;
}
public static void main(String args[])
{
}
}
EXAMPLE WITH PUBLIC
Within the following code fragment, both the connection property and the same connection method are accessible from any point; which for example supposes a problem because not all the classes of your software are going to occupy it
public class Server
{
public String conexion;
public Server(String server)
{
server = server;
}
public static void main(String args[])
{
}
}