0% found this document useful (0 votes)
5 views36 pages

Introduction To Encapsulation and Methods

This lecture focuses on encapsulation and methods in Java, highlighting the importance of data protection through controlled access using getters and setters. Students will learn how to implement these concepts in real programs, including the use of driver programs for execution. Key practices include declaring variables as private and validating data through setter methods.

Uploaded by

alicemahuwi4
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)
5 views36 pages

Introduction To Encapsulation and Methods

This lecture focuses on encapsulation and methods in Java, highlighting the importance of data protection through controlled access using getters and setters. Students will learn how to implement these concepts in real programs, including the use of driver programs for execution. Key practices include declaring variables as private and validating data through setter methods.

Uploaded by

alicemahuwi4
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

CSU07421/ITU07421 – Object-Oriented Programming

Lecture 3 – Introduction to Encapsulation and Methods

Msury Mahunnah, PhD


[Link]@[Link]
1
Encapsulation and Methods in Java
• This lecture introduces important concepts in Java programming, focusing on
encapsulation and how methods such as getters and setters are used to safely
manage data inside classes.
• It explains how these concepts are applied in real programs through the use of
driver programs and the main method.

2
Learning Objectives

• By the end of this lesson, students should be able to explain how encapsulation
protects data and why it is important in object-oriented programming.
• Students should be able to write getter and setter methods correctly and
understand how they are used to access and modify private variables.
• Students should also understand how to use both static and non-static methods
inside a driver program to control program execution.

3
Brief Reminder About Methods
• A method is a reusable block of code that performs a specific task and helps in
organizing large programs into smaller, manageable sections.
• Methods allow programmers to write code once and use it many times, which
reduces repetition and improves readability

4
Why Methods Support Encapsulation
• Methods provide controlled access to class data, which means they act as a safe way
to interact with variables without exposing them directly.
• By using methods, a programmer can decide how data is accessed or modified,
ensuring better control and security.

5
Introduction to Encapsulation
• Encapsulation is a programming concept where data is hidden inside a class and
can only be accessed through specific methods.
• This concept ensures that the internal state of an object cannot be changed directly
from outside the class.

6
Key Idea of Encapsulation
• The main idea of encapsulation is to combine data (variables) and methods
(functions) into a single unit called a class.
• It ensures that sensitive data is protected and only accessible in a controlled and
predictable way.

7
Why Encapsulation is Important
• Encapsulation protects data from accidental changes that could cause errors in the
program.
• It improves security by restricting direct access to variables and forcing interaction
through controlled methods.
• It makes code easier to maintain because changes can be made inside methods
without affecting other parts of the program.

8
Example Without Encapsulation
class Student {
public String name;
}

• In this example, the variable name is public, which means any


part of the program can access and change it directly.
• This lack of control can lead to invalid or unexpected values
being assigned to the variable
9
Problem with Public Variables
• When variables are public, there is no way to control what values are assigned,
which can result in incorrect data being stored.
• It also makes debugging difficult because changes can happen from many different
places in the program

10
Applying Encapsulation Using Private Variables

class Student {
private String name;
}

• The private keyword restricts access so that the variable can


only be accessed within the class itself.
• This forces other parts of the program to use methods to
interact with the variable.

11
Role of Getters and Setters
• Getters and setters are special methods that allow controlled access to private
variables in a class.
• They act as a safe interface between the class and the outside world, ensuring that
data is handled properly.

12
Understanding Getter Methods
• A getter method is used to read or retrieve the value of a private variable without
modifying it.
• It provides a controlled way for other parts of the program to access the value of the
variable.

13
Structure of a Getter Method
public String getName() {
return name;
}

• The method is declared as public so that it can be accessed


from outside the class.
• It returns the value of the private variable without making
any changes to it.
14
Understanding Setter Methods
• A setter method is used to assign or update the value of a private variable in a
controlled way.
• It allows the programmer to include rules or validation before updating the variable

15
Structure of a Setter Method
public void setName(String name) {
[Link] = name;
}

• The keyword this is used to refer to the current object’s


variable and avoid confusion with parameters.
• The setter does not return a value but updates the internal
state of the object.
16
Complete Encapsulation Example
class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}
}

• This class demonstrates how a private variable is accessed and


modified through methods instead of direct access
17
Driver Program Introduction
• A driver program is the part of the program that contains the main method and is
responsible for starting execution.
• It is used to create objects and test how methods work in a real program.

18
Using Getter and Setter in Driver Program

public class Main {


public static void main(String[] args) {
Student s = new Student();

[Link]("Asha");
[Link]([Link]());
}
}

• The setter is used to assign a value to the private variable, and


the getter is used to retrieve and display it.
19
Step-by-Step Execution Explanation
• The program begins execution in the main method, which
acts as the entry point of the application.
• An object of the class is created to access non-static methods
such as getters and setters.
• The setter method assigns a value safely, and the getter
method retrieves it for use

20
Adding Validation in Sette

public void setAge(int age) {


if(age > 0) {
[Link] = age;
}
}

• Validation ensures that only acceptable values are stored,


preventing invalid data from entering the system.

21
Encapsulation Example
class Person {
private String name;
private int age;
}

• Each variable should have its own getter and setter to


maintain full control over access and modification.

22
Multiple Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}

public int getAge() {


return age;
}
public void setAge(int age) {
[Link] = age;
}
• These methods allow controlled access to each variable independently.
23
Driver Program with Multiple Fields
public class Main {
public static void main(String[] args) {
Person p = new Person();

[Link]("John");
[Link](30);

[Link]([Link]());
[Link]([Link]());
}
}
• This shows how multiple setters and getters are used together in a real
program
24
Introduction to Static Methods
• Static methods belong to the class itself and do not require an
object to be created before they are called.
• They are often used for general operations that do not depend
on object-specific data.

25
Example of Static Method in Driver Program

class Helper {
static void displayMessage() {
[Link]("Static method called");
}
}

26
Calling Static Method

public class Main {


public static void main(String[] args) {
[Link]();
}
}

• The method is called using the class name, which shows that
no object is required.

27
Non-Static Methods and Objects
• Non-static methods require an object because they work with
instance-specific data stored in that object.
• Getters and setters are always non-static because they operate
on individual object data

28
Example of Non-Static Method in Driver Program

class Example {
void show() {
[Link]("Non-static method");
}
}

29
Calling Non-Static Method
public class Main {
public static void main(String[] args) {
Example e = new Example();
[Link]();
}
}

• The object e is required to call the method because it belongs


to the instance of the class.

30
Combining Static and Non-Static in One Program

• Static methods can be used alongside non-static methods


within the same program for different purposes.

• Static methods handle general tasks, while non-static


methods handle object-specific tasks such as getters and
setters.

31
Example Combining Both

class Demo {
static void staticMethod() {
[Link]("Static method");
}

void instanceMethod() {
[Link]("Instance method");
}
}

32
Driver Program Combining Both

public class Main {


public static void main(String[] args) {
[Link]();

Demo d = new Demo();


[Link]();
}
}

33
Common Mistakes
• Students often try to access private variables directly instead of using getters and
setters, which breaks encapsulation.
• Many beginners forget to create an object before calling non-static methods, which
results in errors.

34
Best Practices
• Always declare variables as private to ensure data protection and enforce
encapsulation principles.
• Use getters and setters consistently, even when direct access seems easier, to
maintain code quality
• .Include validation in setters to prevent invalid data from being stored in the
program

35
Summary
• Encapsulation is a key concept that protects data and ensures controlled access
through methods.
• Getters and setters are essential tools for implementing encapsulation in Java
programs.
• Driver programs demonstrate how objects, methods, and data work together in real
applications

36

You might also like