Implementing
Encapsulation
Learning Outcomes
❑Recap on Encapsulation
❑Getters and Setters
❑Constructors
Encapsulation == Data Hiding
Object
Interaction
Public Methods Interface
Private Data
Private Methods
Recap: Principle of Encapsulation
“Don’t ask how I do it, but this is what I can do”
- The encapsulated object
“I don’t care how, just do your job, and I’ll do mine”
- One encapsulated object to another
RECAp: Access Modifiers
private
Private features of Sample class
can only be accessed from
within the class itself
Sample Package
Class A
Class C
Class B
protected public
Classes in the package and All classes can access the
all its sub-classes can access public feature
the protected features
Implementing encapsulation
ACCESS MODIFIERS GETTERS AND CONSTRUCTORS
SETTERS
Setters
• Setters are methods that only alter the state of an object by
changing values of the attributes of the class
class Time{
private int hour ;
public void setHour(int h)
{
hour = h;
}
}
Getters
• Getters are methods that only return the state of an object by
returning the values of the attribute of the class
class Time{
private int hour ;
public int getHour()
{
return hour;
}
}
constructors
• Special functions used to initialize objects
o Note that constructor name must match class name
o Constructors have no return type (no void, no static)
• Purpose
o Called when an object of a class is created
o Useful for setting initial values of attributes
constructors
• “new” key word is u sed to create an object of a class.
class Time{
private int hour ;
Time()
{
hour = 5;
}
}
public class TestTime {
public static void main(String
args[]) {
Time t1 = new Time ();
}
Constructors
Default Parameterized
constructor with no parameters, it initializes constructor that requires arguments, it
the instance variables to default values initializes the instance variables to the
given values
Time() Time(int hour)
{ {
------- -------
} }
Multiple constructors
• Different ways to initialize objects based on varying scenarios,
user input, or specific initialization requirements.
• Unique set of parameters list
• Share the same name but differ in parameter list
• Provides flexibility
class Time{
private int hour ;
private int minute ;
Example Time()
hour = 5; Default
minutes = 15;
}
public class TestTime {
Time(int h)
public static void main(String args[]) {
Time t1 = new Time ();//default {
Time t2 = new Time (5);//parameterized hour = h;
Time t3 = new Time (5,15);//parametrized }
} Paramerized
Time(int h,int m)
hour = h;
minutes = m;
}
Conclude
• Encapsulation: bundles data and methods together within a class.
• Control access to data: public getter and setter methods.
• Constructors: Customizable the initialization process of objects using default and parametrized
• Good programming practices by enforcing encapsulated classes