0% found this document useful (0 votes)
2 views

Week -6 Java

The document explains encapsulation in Java, highlighting its role in bundling data and methods within a class while restricting access to internal states through private variables and public getter/setter methods. It also covers the use of packages for organizing related classes, the importance of the Single Responsibility Principle (SRP) in object-oriented design, and provides examples of both violating and adhering to SRP. Overall, it emphasizes improved security, maintainability, and modularity in Java programming.

Uploaded by

Pankaja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Week -6 Java

The document explains encapsulation in Java, highlighting its role in bundling data and methods within a class while restricting access to internal states through private variables and public getter/setter methods. It also covers the use of packages for organizing related classes, the importance of the Single Responsibility Principle (SRP) in object-oriented design, and provides examples of both violating and adhering to SRP. Overall, it emphasizes improved security, maintainability, and modularity in Java programming.

Uploaded by

Pankaja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Week -6 Java

Encapsulation in Java

Encapsulation is one of the fundamental principles of object-oriented programming (OOP), and it refers
to the bundling of data (variables) and methods (functions) that operate on that data into a single unit,
or class. It helps in hiding the internal state of an object and allows controlled access to it via public
methods.

In Java, encapsulation is achieved by:

Private variables: The instance variables of a class are declared as private to prevent direct access from
outside the class.

Public getter and setter methods: These methods provide controlled access to the private variables. A
getter method allows reading the value of a private variable, and a setter method allows modifying the
value of a private variable.

Example:

public class Person {

// Private variables

private String name;

private int age;

// Constructor

public Person(String name, int age) {

this.name = name;

this.age = age;

// Getter method for name

public String getName() {

return name;

}
// Setter method for name

public void setName(String name) {

this.name = name;

// Getter method for age

public int getAge() {

return age;

// Setter method for age

public void setAge(int age) {

if (age > 0) {

this.age = age;

} else {

System.out.println("Age must be positive.");

Key points about Encapsulation:

Data hiding: By using private access modifiers, the internal details of the object (such as variables) are
hidden from outside access.

Access control: The class controls the access to its private fields through the use of getter and setter
methods.

Flexibility: You can change the implementation of a class without affecting the classes that use it, as long
as the public interface (getters and setters) remains the same.
Benefits:

Improved security: Internal object data is protected from unauthorized access and modification.

Control over data: You can enforce rules or constraints through setter methods (e.g., ensuring that age is
always positive).

Easier maintenance: Changes in internal implementation don’t affect external code, as long as the
interface remains consistent.

Simple Example.

public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

this.name = newName;

public class Main {

public static void main(String[] args) {

Person myObj = new Person();

myObj.name = "John"; // error

System.out.println(myObj.name); // error

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.

However, as the name variable is declared as private, we cannot access it from outside this class:

Packages

In Java, **packages** are used to group related classes and interfaces together. They help organize the
code into namespaces, making it easier to manage and avoid naming conflicts. Packages can be built-in
(part of the Java Standard Library) or user-defined.

### Types of Packages:

1. **Built-in Packages**: These come with Java and are available for use. Examples include:

- `java.util` (for collections, utilities, etc.)

- `java.io` (for input/output operations)

- `java.lang` (for fundamental classes like `String`, `Math`, etc.)

- `java.awt` (for graphical user interface components)

2. **User-defined Packages**: These are created by developers to group related classes and interfaces
that are part of a specific application. To create a user-defined package, use the `package` keyword at
the top of your Java source file.

### How to Create and Use a Package:

#### 1. Creating a Package

To define a package, use the `package` keyword followed by the package name. It must be the first
statement in the Java file.
Example:

```java

package com.myapp.utilities;

public class Calculator {

public int add(int a, int b) {

return a + b;

```

#### 2. Using a Package

To use classes from a package, you must import them into your Java file using the `import` statement.

Example:

```java

import com.myapp.utilities.Calculator;

public class Test {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println(calc.add(5, 3)); // Output: 8

```
#### 3. Directory Structure

Packages in Java are mapped to directories in the file system. For the above package
`com.myapp.utilities`, the corresponding directory structure would look like:

```

com/myapp/utilities/Calculator.java

```

#### 4. Access Modifiers with Packages

- **Public**: A class or interface declared as `public` is accessible from any other class in any package.

- **Default (no modifier)**: If no access modifier is provided, the class or member is accessible only
within the same package.

### Why Use Packages?

- **Namespace Management**: Helps avoid name conflicts.

- **Modularity**: Makes the code more modular and organized.

- **Access Control**: Provides access control using the package-private access level.

- **Reusability**: Code can be reused across different applications or projects.

- **Maintainability**: Easier to maintain and manage large projects.

### Single Responsibility Principle (SRP)

**Intent:**

The Single Responsibility Principle (SRP) is one of the five SOLID principles of object-oriented design. It
states that a class should have only one reason to change, meaning that it should have only one job or
responsibility.
**Rules:**

1. A class should only have one job or responsibility.

2. All the methods and properties in a class should align with the class’s core responsibility.

3. If a class has more than one responsibility, it becomes harder to understand, maintain, and modify.
Each responsibility should be encapsulated in its own class.

**Benefits:**

- **Improved maintainability:** A class that has one responsibility is easier to maintain and extend.
Changes in one responsibility won’t affect others.

- **Better readability:** By focusing on a single task, code is easier to understand and navigate.

- **Easier testing:** Since the class is focused on one responsibility, writing unit tests for that class
becomes simpler.

- **Promotes reusability:** Classes designed with SRP are more reusable because they are not tightly
coupled with other concerns.

**Examples in Java:**

1. **Bad Example (Violating SRP):**

```java

class Employee {

private String name;

private int id;

public void saveEmployeeToDatabase() {

// Code to save employee to database

}
public void calculateSalary() {

// Code to calculate employee's salary

// Getter and Setter methods

```

In this example, the `Employee` class is responsible for two tasks:

- Managing employee data.

- Saving the employee data to the database.

- Calculating employee salaries.

This violates the Single Responsibility Principle because the `Employee` class has more than one reason
to change (changes in how the salary is calculated or how the data is saved would require modifying this
class).

2. **Good Example (Following SRP):**

```java

class Employee {

private String name;

private int id;

// Getter and Setter methods


}

class EmployeeDatabase {

public void saveEmployee(Employee employee) {

// Code to save employee to database

class SalaryCalculator {

public double calculateSalary(Employee employee) {

// Code to calculate employee's salary

return 0.0; // Example value

```

In this improved design:

- `Employee` is focused only on holding employee data.

- `EmployeeDatabase` is responsible for saving employee data.

- `SalaryCalculator` handles salary calculation.

Now, each class has one responsibility, making the code easier to maintain, test, and extend.

### Conclusion:

The **Single Responsibility Principle** encourages dividing a system into classes that each handle a
specific task. This results in cleaner, more understandable, and more maintainable code.

You might also like