...
In summary, encapsulation in OOP ensures that data is kept private and can only be accessed through well-defined methods, promoting better organization, modularity, and security in software development. It also enables the concept of information hiding and abstraction, which are essential for building robust and maintainable object-oriented systems.
...
Demo
MailService Class
Code Block | ||
---|---|---|
| ||
package EncapsulationDemo;
public class MailService {
public void sendEmail() {
connect(1);
authenticate();
// Send email
disconnect();
}
private void connect(int timeout) {
System.out.println("Connect");
}
private void disconnect() {
System.out.println("Disconnect");
}
private void authenticate() {
System.out.println("Authenticate");
}
}
|
Driver
Code Block | ||
---|---|---|
| ||
package EncapsulationDemo;
public class EncapsulationMain {
public static void main(String[] args)
{
//create an instance of out MailService
var myMail = new MailService();
System.out.println("Sending mail.....");
myMail.sendEmail();
System.out.println("Notice how we abstract the class functions (Encapsulate)");
}
}
|
...