OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 5 : Accessing Private Members of a Class in Java
Unit - 2
Topic - 5 : Accessing Private Members of a Class in Java
In Java, private members cannot be accessed directly from outside the class.
This is part of encapsulation, where we hide the internal details and expose only the necessary methods to interact with the data.
Why Private Members?
-
They protect the internal state of the object from being modified directly.
-
They help maintain data integrity.
-
They allow controlled access through methods (also called getters and setters).
Example: Using Getters and Setters to Access Private Data
Sample Output
Explanation
-
a – has default (package-private) access, so it can be accessed from the
Main
class since both are in the same package. -
b – is public, so it can be accessed from anywhere.
-
c – is private, so it can only be accessed inside the
Test
class. -
The methods
setc()
andgetc()
are public methods that allow controlled access toc
.
Key Points
-
private members are hidden from outside classes.
-
getter methods return the value of private variables.
-
setter methods modify the value of private variables.
-
This approach is known as data hiding and is a key principle of Object-Oriented Programming (OOP).
Example: Accessing Private Data with Getters and Setters
Sample Output
Explanation
-
The variables
name
andsalary
are private, so they cannot be accessed directly fromEmployeeTest
. -
Getter methods (
getName()
,getSalary()
) are used to retrieve values. -
Setter methods (
setName()
,setSalary()
) are used to update values with an optional validation check (e.g., salary must be positive). -
If invalid data is passed, the setter can reject it and show a message.
Comments
Post a Comment