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

Encapsulation in OOP

The document explains the concept of encapsulation in Object-Oriented Programming (OOP), emphasizing how data and methods are combined within a class to enhance data security and maintainability. It also contrasts Procedural Programming with OOP, highlighting their key differences in focus, approach, and data handling. Additionally, it discusses wrapper classes in Java, detailing their purpose, advantages, and methods for converting primitive types into objects.

Uploaded by

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

Encapsulation in OOP

The document explains the concept of encapsulation in Object-Oriented Programming (OOP), emphasizing how data and methods are combined within a class to enhance data security and maintainability. It also contrasts Procedural Programming with OOP, highlighting their key differences in focus, approach, and data handling. Additionally, it discusses wrapper classes in Java, detailing their purpose, advantages, and methods for converting primitive types into objects.

Uploaded by

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

Class encapsulation basic concept very easily

Encapsulation হলো OOP (Object-Oriented Programming) এর একটি গুরুত্বপূর্ণবৈশিষ্ট্য যেখানে data


(variable) এবং method (function) একসাথে একটি class-এর মধ্যে রাখা হয়।

⭐ সহজ ভাষায় বোঝা যাক:


একটি medicine capsule কল্পনা করুন। এর ভেতরে অনেক উপাদান থাকে, কিন্তু বাইরের মানুষ সরাসরি
সেগুলো পরিবর্তন করতে পারে না। ঠিক তেমনি, encapsulation ব্যবহার করলে class-এর ভেতরের data
বাহির থেকে সরাসরি পরিবর্তন করা যায় না।

🛠 Java-তে Encapsulation:
1. Variable গুলো private করি (যাতে বাইরের কেউ সরাসরি access/change করতে না পারে)।

2. public getter & setter method তৈরি করি (যাতে নিয়ন্ত্রিতভাবে data access/change করা যায়)।

🔹 Code Example:
java Copy Edit

class Person { private String name; // Data hide করা হয়েছে (Encapsulation) // Setter
method (Value set করার জন্য) public void setName(String newName) { name = newName; } //
Getter method (Value read করার জন্য) public String getName() { return name; } } public
class Main { public static void main(String[] args) { Person p1 = new Person();
p1.setName("Rahim"); // Data assign করা হচ্ছে System.out.println(p1.getName()); // Output:
Rahim } }

🔥 সুবিধা:
✅ Data Security: বাহির থেকে সরাসরি পরিবর্তন করা যায় না।
✅ Controlled Access: getter-setter দিয়ে নিয়ন্ত্রণ করা যায়।
✅ Code Maintainability: পরিবর্তন সহজ হয়।

🔹 সহজ ভাষায়:
Encapsulation হলো class-এর ভেতরে data লুকিয়ে রাখা, এবং নির্দিষ্ট method দিয়ে সেটি নিয়ন্ত্রিতভাবে
ব্যবহার করা। 🚀

in english

Encapsulation (Basic Concept in Simple Terms)


Encapsulation is an important concept in Object-Oriented Programming (OOP) where data (variables)
and methods (functions) are wrapped together inside a class.

⭐ Easy Explanation:
Think of a medicine capsule. Inside the capsule, there are different ingredients, but people cannot
access or change them directly. Similarly, in Encapsulation, the internal data of a class cannot be
accessed directly from outside.

🛠 How Encapsulation Works in Java?


1. Make variables private (so they cannot be accessed directly).

2. Use public getter & setter methods (to control access).

🔹 Example in Java:
java Copy Edit

class Person { private String name; // Data is hidden (Encapsulation) // Setter method (To
set value) public void setName(String newName) { name = newName; } // Getter method (To get
value) public String getName() { return name; } } public class Main { public static void
main(String[] args) { Person p1 = new Person(); p1.setName("Rahim"); // Assigning value
System.out.println(p1.getName()); // Output: Rahim } }

🔥 Advantages of Encapsulation:
✅ Data Security – Prevents direct modification of data.
✅ Controlled Access – Access is managed through getter and setter methods.
✅ Code Maintainability – Easy to modify and maintain the code.

🔹 In Simple Words:
Encapsulation means hiding the data inside a class and controlling access using methods. 🚀

Procedural vs Object Oriented Programming

Procedural vs Object-Oriented Programming (OOP)


Both Procedural Programming and Object-Oriented Programming (OOP) are popular programming
paradigms, but they have key differences in how they organize and manage code.
🔹 Procedural Programming (PP)
👉 Definition:
Procedural programming follows a step-by-step (procedure-based) approach, where a program is
divided into functions that operate on data.

👉 Key Features:
✅ Focuses on functions (procedures).
✅ Data and functions are separate.
✅ Uses a top-down approach.
✅ Less secure because data is accessible globally.
✅ Examples: C, Pascal, BASIC
👉 Example in C:
c Copy Edit

#include <stdio.h> // Function to print details void displayDetails(char name[], int age) {
printf("Name: %s\n", name); printf("Age: %d\n", age); } int main() { char name[] = "Rahim";
int age = 25; displayDetails(name, age); // Calling function return 0; }

🔹 Object-Oriented Programming (OOP)


👉 Definition:
Object-Oriented Programming is based on objects and classes, where data and functions are bundled
together.

👉 Key Features:
✅ Focuses on objects.
✅ Uses Encapsulation, Inheritance, Polymorphism, Abstraction.
✅ Follows a bottom-up approach.
✅ More secure because data is hidden inside objects.
✅ Examples: Java, C++, Python
👉 Example in Java:
java Copy Edit

class Person { private String name; // Encapsulated data private int age; // Constructor
public Person(String name, int age) { this.name = name; this.age = age; } // Method to
display details public void displayDetails() { System.out.println("Name: " + name);
System.out.println("Age: " + age); } } public class Main { public static void main(String[]
args) { Person p1 = new Person("Rahim", 25); p1.displayDetails(); // Calling method } }

🔹 Key Differences
Feature Procedural Programming Object-Oriented Programming (OOP)

Focus Functions (Procedures) Objects & Classes

Approach Top-down Bottom-up

Data Handling Data and functions are separate Data and functions are inside objects

Security Less secure (global data access) More secure (data encapsulation)

Code Reusability Low (no inheritance) High (uses inheritance & polymorphism)

Examples C, Pascal, BASIC Java, C++, Python

🚀 Which One is Better?


Use Procedural Programming when writing simple programs or system-level programming (like C
for OS development).

Use OOP when building large, scalable, and maintainable applications (like Java for enterprise
applications).

✅ OOP is more powerful because it supports reusability, scalability, and security! 🚀

What is a wrapper class?

Wrapper Class in Java


A wrapper class in Java is a class that converts primitive data types into objects. Each primitive type
(like int , double , char , etc.) has a corresponding wrapper class.

🔹 Why Do We Need Wrapper Classes?


✅ Primitive types cannot be used in collections (e.g., ArrayList<int> is not allowed,

but ArrayList<Integer> is).


✅ Objects are more flexible (support null values, work with OOP concepts like polymorphism).
✅ Useful for utility methods (e.g., Integer.parseInt("123") to convert a string to an integer).

🔹 Wrapper Classes for Each Primitive Type


Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

🔹 Example: Using Wrapper Class


java Copy Edit

public class WrapperExample { public static void main(String[] args) { int num = 10; //
Primitive type Integer obj = Integer.valueOf(num); // Wrapping (Boxing) int newNum =
obj.intValue(); // Unwrapping (Unboxing) System.out.println("Wrapped Integer: " + obj);
System.out.println("Unwrapped Integer: " + newNum); } }

✅ Output:
sql Copy Edit

Wrapped Integer: 10
Unwrapped Integer: 10

🔹 Autoboxing & Unboxing (Automatic Conversion)


Java automatically converts between primitive types and wrapper objects:

java Copy Edit

public class AutoBoxingExample { public static void main(String[] args) { Integer obj = 20;
// Autoboxing (int → Integer) int num = obj; // Unboxing (Integer → int)
System.out.println("Autoboxed: " + obj); System.out.println("Unboxed: " + num); } }

✅ Output:
makefile Copy Edit

Autoboxed: 20
Unboxed: 20

🔹 Useful Wrapper Class Methods


Wrapper classes provide useful methods:

java Copy Edit

public class WrapperMethodsExample { public static void main(String[] args) { // Convert


String to int int num = Integer.parseInt("123"); // Convert int to String String str =
Integer.toString(456); // Check max value of int int maxVal = Integer.MAX_VALUE;
System.out.println("Parsed int: " + num); System.out.println("Converted String: " + str);
System.out.println("Max Value of int: " + maxVal); } }

✅ Output:
arduino Copy Edit

Parsed int: 123


Converted String: 456
Max Value of int: 2147483647

🔹 Summary
✔ Wrapper classes allow primitive types to be used as objects.
✔ Autoboxing & Unboxing simplify conversions.
✔ Wrapper classes provide useful methods like parseInt() , toString() , and MAX_VALUE .
✔ Useful in collections, multithreading, and object-oriented programming. 🚀

10.7 Describe primitive-type wrapper classes.

10.7 Primitive-Type Wrapper Classes


In Java, primitive-type wrapper classes are special classes that encapsulate (wrap) primitive data types
into objects. Each primitive type has a corresponding wrapper class in the java.lang package.

🔹 Why Use Wrapper Classes?


1. Object-Oriented Programming – Java collections ( ArrayList , HashMap ) work with objects, not
primitives.

2. Utility Methods – Wrapper classes provide methods to convert values ( parseInt() , toString() ).

3. Autoboxing & Unboxing – Java automatically converts between primitive types and objects.

🔹 Wrapper Classes for Primitive Types


Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

🔹 Example: Wrapping and Unwrapping


java Copy Edit

public class WrapperExample { public static void main(String[] args) { int num = 10; //
Wrapping (Boxing) Integer obj = Integer.valueOf(num); // Unwrapping (Unboxing) int newNum =
obj.intValue(); System.out.println("Wrapped Integer: " + obj);
System.out.println("Unwrapped Integer: " + newNum); } }

✅ Output:
sql Copy Edit

Wrapped Integer: 10
Unwrapped Integer: 10

🔹 Autoboxing & Unboxing (Automatic Conversion)


Java allows automatic conversion between primitives and wrapper objects:

java Copy Edit

public class AutoBoxingExample { public static void main(String[] args) { Integer obj = 20;
// Autoboxing (int → Integer) int num = obj; // Unboxing (Integer → int)
System.out.println("Autoboxed: " + obj); System.out.println("Unboxed: " + num); } }

✅ Output:
makefile Copy Edit

Autoboxed: 20
Unboxed: 20

🔹 Useful Methods in Wrapper Classes


Wrapper classes provide many useful methods:

java Copy Edit


public class WrapperMethodsExample { public static void main(String[] args) { // Convert
String to int int num = Integer.parseInt("123"); // Convert int to String String str =
Integer.toString(456); // Check max value of int int maxVal = Integer.MAX_VALUE;
System.out.println("Parsed int: " + num); System.out.println("Converted String: " + str);
System.out.println("Max Value of int: " + maxVal); } }

✅ Output:
arduino Copy Edit

Parsed int: 123


Converted String: 456
Max Value of int: 2147483647

🔹 Summary
✔ Wrapper classes allow primitive types to be used as objects.
✔ Autoboxing & Unboxing simplify conversions.
✔ Wrapper classes provide useful methods like parseInt() , toString() , and MAX_VALUE .

✔ Used in collections, multithreading, and object-oriented programming. 🚀

10.8 Can each of the following statements be compiled?


a. Integer i = new Integer("23");
b. Integer i = new Integer(23);
c. Integer i = Integer.valueOf("23");
d. Integer i = Integer.parseInt("23", 8);
e. Double d = new Double();
f. Double d = Double.valueOf("23.45");
g. int i = (Integer.valueOf("23")).intValue();
h. double d = (Double.valueOf("23.4")).doubleValue();
i. int i = (Double.valueOf("23.4")).intValue();
j. String s = (Double.valueOf("23.4")).toString(); Answer properly
with question & answer

10.8 Can each of the following statements be compiled?


Let's analyze each statement one by one:

a. Integer i = new Integer("23");

✅ Valid (Compiles), but deprecated in Java 9+


👉 Since Java 9, new Integer(String) is deprecated. Use Integer.valueOf("23") instead.

b. Integer i = new Integer(23);

✅ Valid (Compiles), but deprecated in Java 9+


👉 Since Java 9, new Integer(int) is deprecated. Use Integer.valueOf(23) instead.

c. Integer i = Integer.valueOf("23");

✅ Valid (Compiles)
👉 Integer.valueOf("23") converts the string "23" into an Integer object.

d. Integer i = Integer.parseInt("23", 8);

✅ Valid (Compiles)
👉 Integer.parseInt("23", 8) converts "23" from octal (base 8) to decimal ( 2×8 + 3 = 19 ).

👉 The result is int , but it should be stored in int , not Integer .


✔ Corrected version:
java Copy Edit

int i = Integer.parseInt("23", 8); // i = 19

e. Double d = new Double();

❌ Invalid (Compilation Error)


👉 No default constructor in Double . Must pass a value.
✔ Corrected version:
java Copy Edit

Double d = new Double(23.45); // OR use Double.valueOf(23.45)

f. Double d = Double.valueOf("23.45");

✅ Valid (Compiles)
👉 Double.valueOf("23.45") converts the string "23.45" into a Double object.

g. int i = (Integer.valueOf("23")).intValue();

✅ Valid (Compiles)
👉 Integer.valueOf("23") creates an Integer object, then .intValue() extracts the int value.

✔ Equivalent:
java Copy Edit

int i = Integer.parseInt("23"); // Simpler way

h. double d = (Double.valueOf("23.4")).doubleValue();

✅ Valid (Compiles)
👉 Double.valueOf("23.4") creates a Double object, then .doubleValue() extracts the double value.

✔ Equivalent:
java Copy Edit

double d = Double.parseDouble("23.4"); // Simpler way

i. int i = (Double.valueOf("23.4")).intValue();

✅ Valid (Compiles)
👉 Double.valueOf("23.4") creates a Double object,
then .intValue() converts 23.4 to 23 (truncates decimal).

✔ Equivalent:
java Copy Edit

int i = (int) Double.parseDouble("23.4"); // Alternative

j. String s = (Double.valueOf("23.4")).toString();

✅ Valid (Compiles)
👉 Double.valueOf("23.4") creates a Double object, then .toString() converts it to "23.4" .

✔ Equivalent:
java Copy Edit

String s = String.valueOf(23.4);

Final Answer Summary


Statement Compiles? Reason / Correction

a. Integer i = new Integer("23"); ✅ Valid but deprecated since Java 9.

b. Integer i = new Integer(23); ✅ Valid but deprecated since Java 9.

c. Integer i = Integer.valueOf("23"); ✅ Correct usage of Integer.valueOf() .

d. Integer i = Integer.parseInt("23", 8); ✅ Should be stored in int instead


of Integer .

e. Double d = new Double(); ❌ No default constructor for Double .

f. Double d = Double.valueOf("23.45"); ✅ Correct usage of Double.valueOf() .

g. int i = (Integer.valueOf("23")).intValue(); ✅ Correct usage of intValue() .

h. double d = ✅ Correct usage of doubleValue() .


(Double.valueOf("23.4")).doubleValue();

i. int i = (Double.valueOf("23.4")).intValue(); ✅ Converts double to int (truncates


decimal).
Statement Compiles? Reason / Correction

j. String s = ✅ Converts Double to String .


(Double.valueOf("23.4")).toString();

✅ Best Practice: Avoid deprecated constructors and


use valueOf() or parseInt()/parseDouble() instead. 🚀

10.9 How do you convert an integer into a string? How do you


convert a numeric string
into an integer? How do you convert a double number into a
string? How do you
convert a numeric string into a double value? Answer properly with
question & answer

10.9 Conversions Between Numbers and Strings in Java


Below are different ways to convert integers, doubles, and strings in Java.

1️⃣ How do you convert an integer into a string?


✅ Answer: Use String.valueOf(int) or Integer.toString(int)

✔ Example:
java Copy Edit

int num = 123; String str1 = String.valueOf(num); // Method 1 String str2 =


Integer.toString(num); // Method 2 System.out.println("String value: " + str1);

✅ Output:
arduino Copy Edit

String value: 123

2️⃣ How do you convert a numeric string into an integer?


✅ Answer: Use Integer.parseInt(String) or Integer.valueOf(String)

✔ Example:
java Copy Edit

String str = "456"; int num1 = Integer.parseInt(str); // Method 1 int num2 =


Integer.valueOf(str); // Method 2 System.out.println("Integer value: " + num1);

✅ Output:
sql Copy Edit

Integer value: 456

3️⃣ How do you convert a double number into a string?


✅ Answer: Use String.valueOf(double) or Double.toString(double)

✔ Example:
java Copy Edit

double num = 23.45; String str1 = String.valueOf(num); // Method 1 String str2 =


Double.toString(num); // Method 2 System.out.println("String value: " + str1);

✅ Output:
arduino Copy Edit

String value: 23.45

4️⃣ How do you convert a numeric string into a double value?


✅ Answer: Use Double.parseDouble(String) or Double.valueOf(String)

✔ Example:
java Copy Edit

String str = "78.9"; double num1 = Double.parseDouble(str); // Method 1 double num2 =


Double.valueOf(str); // Method 2 System.out.println("Double value: " + num1);
✅ Output:
kotlin Copy Edit

Double value: 78.9

🔹 Summary Table
Conversion Method 1 Method 2

Integer → String String.valueOf(int) Integer.toString(int)

String → Integer Integer.parseInt(String) Integer.valueOf(String)

Double → String String.valueOf(double) Double.toString(double)

String → Double Double.parseDouble(String) Double.valueOf(String)

✅ Best Practice: Use parseInt() and parseDouble() for conversions from strings to numbers. 🚀

10.10 Show the output of the following code.


public class Test {
public static void main(String[] args) {
Integer x = new Integer(3);
System.out.println(x.intValue());
System.out.println(x.compareTo(new Integer(4)));
}
}Answer properly with question & answer

10.10 Show the Output of the Following Code

Given Code:

java Copy Edit

public class Test { public static void main(String[] args) { Integer x = new Integer(3);
System.out.println(x.intValue()); System.out.println(x.compareTo(new Integer(4))); } }

Step-by-Step Execution:
1. Integer x = new Integer(3);

Creates an Integer object with the value 3 .

Note: new Integer(int) is deprecated in Java 9+. The recommended approach is Integer x
= Integer.valueOf(3); .

2. System.out.println(x.intValue());

intValue() returns the primitive int value stored in x .

Output: 3

3. System.out.println(x.compareTo(new Integer(4)));

compareTo(Integer anotherInteger) compares x ( 3 ) with 4 .

Rules for compareTo() method:

Returns 0 if x == 4

Returns -1 if x < 4 (because 3 < 4 )

Returns 1 if x > 4

Here, 3 < 4 , so it returns -1 .

Output:
diff Copy Edit

3
-1

Final Answer Summary


Statement Output Explanation

System.out.println(x.intValue()); 3 intValue() returns the primitive value


of x .

System.out.println(x.compareTo(new -1 3 < 4 , so compareTo() returns -1 .


Integer(4)));
🚀 Best Practice: Instead of new Integer(3) , use Integer.valueOf(3) for better performance and to

avoid deprecation warnings.

You might also like