0% found this document useful (0 votes)
6 views17 pages

Java Encapsulation and Inheritance Explained

Uploaded by

bhavyakgandhwani
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)
6 views17 pages

Java Encapsulation and Inheritance Explained

Uploaded by

bhavyakgandhwani
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

Encapsulation & Inheritance

Visibility modes used in Java are:

1.​ private — private members are accessible only inside their


own class.
2.​ protected — protected members are accessible inside
their own class, classes within the package and
subclasses.
3.​ public — public members are accessible in all the classes.

Use of private data members

⭐ What are Private Data Members in Java?


In Java, private data members are variables of a class that are
declared using the keyword private.​
This means they cannot be accessed directly from outside the class.

Why do we use private?

Because of the OOP concept called Encapsulation.​


Encapsulation means binding data and methods together and
protecting data from unauthorized access.

⭐ Example
class Student {
private String name; // private data member
private int age; // private data member

// Setter method (to store data)


public void setData(String n, int a) {
name = n;
age = a;
}

// Getter method (to display data)


public void showData() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

class Main {
public static void main(String args[]) {
Student obj = new Student();
[Link]("Rahul", 15);
[Link]();
}
}

⭐ Key Points to Remember


Feature Explanation
Keyword used private
Access level Only inside the same class
Why used? To protect data (Encapsulation)
How to access private data? Through getter and setter methods

🧠 Advantages of Private Data Members


1️⃣ Protects data from direct modification​
2️⃣ Helps in maintaining data security​
3️⃣ Allows validation before updating values​
4️⃣ Supports Encapsulation (important OOP concept)

❌ What happens if you try to access them directly?


[Link] = "Rahul"; // ❌ Error! name is private
Student obj = new Student();

You will get an error because private data cannot be accessed outside
the class.

Use of private member methods with getValue():

⭐ What is a Private Member Method?


A private member method is a method declared with the keyword
private. It can be used only inside the same class and cannot be
called from outside the class.
⭐ Why use getValue() ?
In ICSE Java, getValue() is commonly used as a public method to
access a value stored in a private data member.​
It follows the encapsulation rule: data is private, but methods allow
controlled access.

⭐ Example Program
class NumberWork {

private int num; // private data member

private int findSquare() { // private member method

return num * num;

public void getValue(int n) { // public method to assign value

num = n;

int sq = findSquare(); // calling private method inside class

[Link]("Number = " + num);

[Link]("Square = " + sq);

class MainClass {

public static void main(String args[]) {

NumberWork obj = new NumberWork();

[Link](7); // allowed

// [Link](); //
accessed
❌ Error: private method cannot be
}

⭐ Explanation
Element Purpose

private int num; private data member

private int findSquare() private helper method to calculate square

public void getValue(int used to assign value and call private method
n)

findSquare() is not accessible in main(), but it can be used inside


getValue() because it is within the same class.

⭐ Output
Number = 7

Square = 49

⭐ Why use private methods with getValue()?


✔ Ensures data protection (Encapsulation)​
✔ Internal calculations are hidden and secured​
✔ Only getValue() controls how data is processed​
✔ Prevents wrong or direct usage of logic from outside

Important-

Private member methods are used to perform internal


operations within a class and cannot be accessed from
outside. getValue() is a public method that can receive
data and call private methods, thus supporting
encapsulation.
⭐ Encapsulation
📌 Definition
Encapsulation is an Object-Oriented Programming (OOP) principle in
which data (variables) and methods (functions) that operate on the
data are bound together into a single unit called a class, and the data
is kept safe from direct outside access using access modifiers like
private.

In simple words:

➡ Encapsulation means wrapping data and methods into one unit


and protecting the data from direct access.

📌 Why is Encapsulation needed?


Encapsulation helps to:

✔ Protect data from unauthorized access​


✔ Prevent accidental changes to important variables​
✔ Allow controlled access using methods (getters/setters)​
✔ Improve security and maintain data integrity

📌 How do we achieve Encapsulation in Java?


Encapsulation is done by:

1️⃣ Making data members private


private int age;

2️⃣ Accessing data through public getter & setter methods


public void setAge(int a) { // setter
age = a;
}

public int getAge() { // getter


return age;
}

📌 Example
class Student {
private String name; // private data
private int marks;

public void setData(String n, int m) {


name = n;
marks = m;
}

public void showData() {


[Link]("Name: " + name);
[Link]("Marks: " + marks);
}
}

class Main {
public static void main(String args[]) {
Student obj = new Student();
[Link]("Rahul", 88); // allowed

}
[Link]();
// [Link] = "Amit"; ❌ Error: name is private

}
📌 Output:
Name: Rahul
Marks: 88

📌 Diagram (for notebook)


+------------------------+
| Student |
+------------------------+
| - name : String | ← private data
| - marks : int |
+------------------------+
| + setData() | ← public methods
| + showData() |
+------------------------+

✦ Encapsulation is the process of wrapping data and methods into a


single unit (class) and restricting direct access to data using private
members.​
✦ It helps in data hiding and security.​
✦ Data is accessed using public methods such as getters and
setters.

📘 Data Hiding
⭐ Definition
Data Hiding is an object-oriented programming (OOP) feature in which
the data of a class is kept private so that it cannot be accessed or
changed directly from outside the class.

It protects the data from unauthorized access and accidental


modification.

⭐ Data is kept safe by using the private access modifier, and


access is provided using public methods (getters and setters).

⭐ Example
class Employee {
private String name; // data hidden

private double salary; // data hidden

public void setData(String n, double s) {

name = n;

salary = s;

public void showData() {

[Link]("Name: " + name);

[Link]("Salary: " + salary);

class Main {

public static void main(String args[]) {

Employee e = new Employee();

[Link]("Rohan", 35000);

[Link]();

// [Link] = 50000; // ❌ Error: salary is private


}

✔ Result of Data Hiding:

No one can directly change salary or name from outside the class.
⭐ Why is Data Hiding Important?
Advantage Explanation

🛡 Security Prevents misuse of data

🎯 Control Allows controlled access through


methods

⚙ Reliability Reduces errors and protects data


integrity

🔐 Encapsulation Supports the main OOP concept of


encapsulation

⭐ Relation With Encapsulation


Data hiding is a part of Encapsulation.

Encapsulation = Data Hiding + Methods to access data

Note-

✦ Data Hiding means protecting data of a class from direct access


using the private keyword.​
✦ We provide controlled access using public getter and setter
methods.​
✦ It ensures security, control, and reliability of data.

Example-

+------------------------+

| Employee |

+------------------------+

| - name : String | ← Private Data (Hidden)

| - salary : double |

+------------------------+
| + setData() | ← Public Methods

| + showData() |

+------------------------+

📘 Scope of Variables
⭐ Definition
Scope of a variable refers to the region or part of a program where a
variable can be accessed or used.

If a variable is outside its scope, the program cannot use it.

⭐ Types of Variable Scope in Java (Class 10 Level)


Type of Variable Where it is declared Where it can be used

Instance / Class Inside a class, but Anywhere inside the


Variable outside any method class (in all methods)

Local Variable Inside a method or Only inside that method


block or block

1️⃣ Instance (Class) Variables


●​ Declared inside the class, outside methods​

●​ Exist as long as the object exists​

●​ Accessible to all methods of that class​

Example:

class Example {

int x = 10; // instance variable


public void show() {

[Link](x); // allowed

2️⃣ Local Variables


●​ Declared inside a method, loop, or block​

●​ Created when the method starts and destroyed when it ends​

●​ Cannot be used outside that method/block​

Example:

class Demo {

public void display() {

int y = 20; // local variable

[Link](y);

Trying to use y outside the method will give an error.

⭐ Code Example Showing Both Scopes


class ScopeTest {

int a = 5; // instance variable

public void test() {

int b = 10; // local variable

[Link]("a = " + a); // allowed

[Link]("b = " + b); // allowed

}
public void show() {

[Link](a); // allowed

// [Link](b); ❌ Error: b not in scope


}

⭐ Key Differences
Instance Variable Local Variable

Declared outside methods Declared inside a method/block

Accessible throughout class Accessible only inside that


method

Exists while object exists Exists only during method


execution

Has default values No default values (must be


initialized)

⭐ Important -
✦ Scope means visibility and accessibility of a variable.​
✦ Local variables must be initialized before use.​
✦ Instance variables have default values (e.g., int = 0, boolean =
false, objects = null).
📘 Inheritance
⭐ Definition
Inheritance is an Object-Oriented Programming (OOP) feature in
which one class (child class / subclass) acquires the properties and
methods of another class (parent class / superclass).

In simple words:

➡ Inheritance allows us to reuse code by creating a new class from


an existing class.

⭐ Keywords Used in Java


class subclass extends superclass

The keyword extends is used to perform inheritance.

⭐ Types of Inheritance 1️⃣ Single Inheritance


👉 One superclass and one subclass.
Example:

class Animal {

void eat() {

[Link]("Animals eat food");

class Dog extends Animal {

void bark() {
[Link]("Dog barks");

class Main {

public static void main(String args[]) {

Dog d = new Dog();

[Link](); // inherited method

[Link]();

2️⃣ Multilevel Inheritance


👉 Inherits through more than one level (Grandparent → Parent →
Child).

Example:

class Animal {

void eat() {

[Link]("Animals eat food");

class Dog extends Animal {

void bark() {

[Link]("Dog barks");

}
class Puppy extends Dog {

void weep() {

[Link]("Puppy weeps");

class Main {

public static void main(String args[]) {

Puppy p = new Puppy();

[Link](); // from Animal

[Link](); // from Dog

[Link](); // from Puppy

⭐ Advantages of Inheritance
Benefit Explanation

🔁 Code Reusability Avoids rewriting common code

🏷 Organization Classes can be grouped logically

✨ Easy Maintenance Changes in base class reflect in subclasses

🔓 Extensibility Features can be easily extended


⭐ Important Terms
Term Meaning

Superclass / Parent class The class whose features are


inherited

Subclass / Child class The class that inherits features

extends Java keyword used for


inheritance

⭐📌 Definition

Inheritance is an OOP principle in which one class inherits the


properties and methods of another class using the extends keyword.
It helps in code reusability and easier program maintenance.

📌 Example
class A { void show() { } }

class B extends A { }

⭐ Diagram
Animal ← Superclass

Dog ← Subclass
Multilevel:

Animal → Dog → Puppy

You might also like