Week -6 Java
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.
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:
// Private variables
// Constructor
this.name = name;
this.age = age;
return name;
}
// Setter method for name
this.name = name;
return age;
if (age > 0) {
this.age = age;
} else {
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.
// Getter
return name;
// Setter
this.name = newName;
System.out.println(myObj.name); // error
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.
1. **Built-in Packages**: These come with Java and are available for use. Examples include:
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.
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;
return a + b;
```
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;
```
#### 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
```
- **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.
- **Access Control**: Provides access control using the package-private access level.
**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:**
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:**
```java
class Employee {
}
public void calculateSalary() {
```
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).
```java
class Employee {
class EmployeeDatabase {
class SalaryCalculator {
```
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.