Encapsulation in Java
Encapsulation in Java
Output
Name=> Geek
// Driver Class
public class Geeks {
// main function
public static void main(String[] args)
{
// person object created
Person p = new Person();
p.setName("John");
p.setAge(30);
// Using methods to get the values from the
// variables
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}
Output
Name: John
Age: 30
Example 2: In this example, we use abstraction to hide the
implementation and show the functionality.
class Area {
private int l; // this value stores length
private int b; // this value stores breadth
Output
Area: 32
Example 3: The program to access variables of the class
Encapsulate Demo is shown below:
// Java program to demonstrate
// Java encapsulation
class Encapsulate {
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
Output
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51