0% found this document useful (0 votes)
6 views4 pages

Encapsulation Example

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

Encapsulation Example

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Encapsulation

Encapsulation is one of the core principles of Object-Oriented


Programming that involves wrapping data (variables) and
code (methods) into a single unit (class) while restricting
direct access to some details of the object. This is achieved
using private variables and public getter/setter methods.
1.) Encapsulation meaning that is to make sure that
sensitive data is hidden from users.
2.) Declare class variables as private.
3.) Provide public get and set methods to access and update
the value of private variables.
Get and Set
Private variables can only be accessed within the same
class.
No access to an outside class.
It is possible to access them if we provide public get and set
methods.
The get method returns the variable value and the set
method sets the value.
Example:-
Public class Person {
Private String name;
Public String getName() { //getter
Return name;
}
public void SetName (String newName) {
this.name = newname;
}
}

Public class Main1{


Public static void main(String[] args){
Person myObj = new Person();
myObj.setName(“Jimmy”);
System.out.println(myObj.getName());
}}

The get method returns the value of the variable name.


The set method takes a parameter newname and assigns it
to the name variable. The this keyword is used to refer to
the current object.
Example:-
// Encapsulated class
class Person {
private String name; // Private variable (cannot be
accessed directly)
private int age;
// Public getter method for name
public String getName() {
return name;
}

// Public setter method for name


public void setName(String name1) {
this.name = name1;
}

// Public getter method for age


public int getAge() {
return age;
}

// Public setter method for age


public void setAge(int age1) {
if (age1 > 0) {
this.age = age1;
} else {
System.out.println("Age must be positive!");
}
}
}

public class Main {


public static void main(String[] args) {
Person p = new Person();

// Setting values using setter methods


p.setName("John Doe");
p.setAge(25);

// Getting values using getter methods


System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}

You might also like