0% found this document useful (0 votes)
3 views10 pages

Week 6 Java Notes

Uploaded by

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

Week 6 Java Notes

Uploaded by

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

Object Oriented Programming and Design with Java

20CS43P

WEEK 6

 OOP concepts: Encapsulation


 Concept; what is encapsulation? How to achieve encapsulation in java;
 Packages;
 Single Responsibility Principle: Intent; Rules; Benefits; example

What is Encapsulation in Java?

Encapsulation in Java is a mechanism to wrap up variables(data) and methods(code) together as


a single unit. It is the process of hiding information details and protecting data and behavior of
the object. It is one of the four important OOP concepts. The encapsulate class is easy to test, so
it is also better for unit testing.

Data Hiding in Java

Data Hiding in Java is hiding the variables of a class from other classes. It can only be accessed
through the method of their current class. It hides the implementation details from the users. But
more than data hiding, it is meant for better management or grouping of related data.

To achieve a lesser degree of encapsulation in Java, you can use modifiers like “protected” or
“public”. With encapsulation, developers can change one part of the code easily without
affecting other.

1
Object Oriented Programming and Design with Java
20CS43P

Getter and Setter in Java

Getter and Setter in Java are two conventional methods used to retrieve and update values of a
variable. They are mainly used to create, modify, delete and view the variable values.

The setter method is used for updating values.

The getter method is used for reading or retrieving the values.

They are also known as an accessor and mutator.

class Account{
private int account_number;
private int account_balance;
// getter method
public int getBalance() {
return this.account_balance;
}
// setter method
public void setNumber(int num) {
this.account_number = num;
}
}

Example1:

class MyClass
{
private int var1;

// Getter function
public int getVar1()
{
return var1;
}

// Setter function
public void setVar1(int v)
{
this.var1 = v;
}
}
public class HelloWorld
2
Object Oriented Programming and Design with Java
20CS43P
{

public static void main(String []args)


{
MyClass myObject = new MyClass(); // creating class's object
myObject.setVar1(20); // invoking setter to set value
System.out.println(myObject.getVar1());
// get private variable value through getter function
}
}

Output:
20

Example2:

class User
{
private String firstName; // private data
private String lastName;
private int age;
public String userID; // assuming IDs can be public

User (String firstName, String lastName, int age, String userID)


{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.userID = userID;
}

// Getter function
public String getFirstName()
{
return this.firstName;
}

// Getter function
public String getLastName()
{
3
Object Oriented Programming and Design with Java
20CS43P
return this.lastName;
}

// Getter function
public int getAge()
{
return this.age;
}

// Getter function
public String getUserID()
{
return this.userID;
}

// Setter function
public void setAge(int age)
{
this.age = age;
System.out.println("User #" + this.userID + "'s age updated to " + age);
// printing update information
}

public class EnCap


{

public static void main(String []args)


{
User user1 = new User("John", "Doe", 28, "ABC123"); // creating new user
User user2 = new User("Jane", "Doe", 31, "ABC121");
User user3 = new User("Shawn", "Doe", 27, "ABC122");

System.out.println("User info -- Name: " + user1.getFirstName() + " " +


user1.getLastName() + "; ID: " + user1.getUserID() + "; Age: " + user1.getAge());
System.out.println("User info -- Name: " + user2.getFirstName() + " " +
user2.getLastName() + "; ID: " + user2.getUserID() + "; Age: " + user2.getAge());
System.out.println("User info -- Name: " + user3.getFirstName() + " " +
user3.getLastName() + "; ID: " + user3.getUserID() + "; Age: " + user3.getAge());

user1.setAge(29); // updating age through setter


4
Object Oriented Programming and Design with Java
20CS43P

System.out.println("User info -- Name: " + user1.getFirstName() + " " +


user1.getLastName() + "; ID: " + user1.getUserID() + "; Age: " + user1.getAge());
// checking update
}
}

Output:

User info -- Name: John Doe; ID: ABC123; Age: 28


User info -- Name: Jane Doe; ID: ABC121; Age: 31
User info -- Name: Shawn Doe; ID: ABC122; Age: 27
User #ABC123's age updated to 29
User info -- Name: John Doe; ID: ABC123; Age: 29

Advantages of Encapsulation in Java

 Encapsulation is binding the data with its related functionalities. Here functionalities mean
“methods” and data means “variables”
 So we keep variable and methods in one place. That place is “class.” Class is the base for
encapsulation.
 With Java Encapsulation, you can hide (restrict access) to critical data members in your code,
which improves security
 As we discussed earlier, if a data member is declared “private”, then it can only be accessed
within the same class. No outside class can access data member (variable) of other class.
 However, if you need to access these variables, you have to use public “getter” and “setter”
methods.

Single Responsibility Principle


As the name suggests, this principle states that each class should have one responsibility, one
single purpose. This means that a class will do only one job, which leads us to conclude it should
have only one reason to change.

We don’t want objects that know too much and have unrelated behavior. These classes are harder
to maintain. For example, if we have a class that we change a lot, and for different reasons, then
this class should be broken down into more classes, each handling a single concern. Surely, if an
error occurs, it will be easier to find.

Benefits of Single Responsibility Principle

 When an application has multiple classes, each of them following this principle, then the
applicable becomes more maintainable, easier to understand.
 The code quality of the application is better, thereby having fewer defects.
5
Object Oriented Programming and Design with Java
20CS43P
 Onboarding new members are easy, and they can start contributing much faster.
 Testing and writing test cases is much simpler

Example1:

IEmployeeStore.java
public interface IEmployeeStore
{
public Employee getEmployeeById(Long id);

public void addEmployee(Employee employee);

public void sendEmail(Employee employee, String content);


}

EmployeeStore.java

public class EmployeeStore implements IEmployeeStore


{
@Override
public Employee getEmployeeById(Long id) {
return null;
}

@Override
public void addEmployee(Employee employee) {

@Override
public void sendEmail(Employee employee, String content) {
}
}

 Above class seems good on any normal application. using EmployeeStore, are able to get/add
employees and send email to them.

 Now suppose after product release, we got requirement that email content can be of two
types i.e. HTML and text. Above class supprt only text content. What you will do?

6
Object Oriented Programming and Design with Java
20CS43P
 One way to solve this issue is create another method sendHtmlEmail() – but what happens
when we are asked to support different protocols for sending emails for both content types.
Overall class will look very ugly and difficult to read and maintain.

 And there is always a chance that during modification, some developer can change the logic
used for get/add employee methods if they are shared.

Solution is SRP Principle


To solve this issue, we must pull out the email capability to separate interface and classes which
specifically handle only email related functionality. This way, we are sure that other features are
not impacted.

Based on our assumptions, we can abstract out two interfaces IEmailSender and IEmailContent.
First interface is responsible for email sending process and second interface is responsible for
passing the email content and it’s type.
The refactored classes are given below,

IEmployeeStore.java
public interface IEmployeeStore
{
public Employee getEmployeeById(Long id);

public void addEmployee(Employee employee);


}

EmployeeStore.java
public class EmployeeStore implements IEmployeeStore
{
//inject in runtime
private IEmailSender emailSender;

@Override
public Employee getEmployeeById(Long id) {
return null;
}

@Override
public void addEmployee(Employee employee) {
}
}

7
Object Oriented Programming and Design with Java
20CS43P
IEmailSender.java
public interface IEmailSender
{
public void sendEmail(Employee employee, IEmailContent content);
}

EmailSender.java
public class EmailSender implements IEmailSender
{
@Override
public void sendEmail(Employee employee, IEmailContent content) {
//logic
}
}
IEmailContent.java
public interface IEmailContent {

EmailContent.java
public class EmailContent implements IEmailContent
{
private String type;
private String content;
}
Now if we want to change the email functionality, we will change EmailSender class only. Any
change to employee CRUD operations will happen in EmployeeStore only. Any change in one
capability will not change other one by mistake. They are not more easy to read and maintain as
well.
Note: CRUD Operation In Java is an acronym for CREATE, READ, UPDATE and DELETE.
Example2:
class Calculator
{
public void add(int x, int y)
{
System.out.println(x + y);
}
}

class CalculatingMachine
{

8
Object Oriented Programming and Design with Java
20CS43P
public static void add(int x, int y)
{
System.out.println(x + y);
}
}

Now everything looks great. It's time to remember SRP: every class should have only one
responsibility. What responsibilities does this class have?

 It is responsible for the logic to add 2 numbers.


 It is responsible for displaying the result.
 It is responsible for choosing the output stream.

There are three responsibilities, so SRP is violated. The responsibilities described here are
basically "the facts" I've mentioned in the very beginning. The idea is to write three classes so
that each of them was responsible for one fact.

class Calculator
{
// this class is only responsible for adding numbers
public static int add(int x, int y)
{
return x + y;
}
}

class PrintStreamDecider
{
// this class is only responsible for deciding
// which PrintStream is to be used

public static PrintStream getPrintStream()


{
return System.out;
}
}

class ResultPrinter
{
// this class is only responsible for printing int values
public static void printResult(int value)
{
PrintStreamDecider.getPrintStream().print(value);
9
Object Oriented Programming and Design with Java
20CS43P
}
}
class CalculatingMachine
{
// this class is only responsible for processing the add-two-numbers request
public static void processTheAddCommand(int x, int y)
{
int result = Calculator.add(x, y);
ResultPrinter.printResult(result);
}
}

 CalculatingMachine is not aware of what the "add" operation is, it is only aware of the
intention.
 CalculatingMachine is not aware of what is PrintStream, it is not aware about how to print
the result at all. It is only aware of the intention that result should be printed.

There are a number of ensured benefits of using the Single Responsibility Principle – both
to the code and the programmer.

1. Easy to extend the class with functionality because unrelated code isn’t present in the same
class.
2. Dependency management aspects between classes become easier to manage since the code is
grouped well.
3. Code changes are isolated and the unknown impacts on other areas of the system are greatly
reduced.
4. Classes will be a lot smaller and hence it will is easy to understand the code. A good set of
naming conventions for the classes and the methods in addition to adhering to the principle
further increase the benefits.
5. Easy to identify defects and fix problems in the code.
6. Easier to write optimal tests since the functionality provided by the class is much clearer.
7. On-boarding a new team member is easier since the code is well-organized and easy to
understand.

10

You might also like