0% found this document useful (0 votes)
4 views12 pages

Class and Object

The document explains the concepts of classes and objects in Java, detailing their definitions, syntax, and examples. It also covers constructors, including types and differences from methods, as well as local and instance variables, and the use of the 'this' keyword. Additionally, it discusses encapsulation, its importance, and how to implement it in Java for data security and control.

Uploaded by

sagarbabail18
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)
4 views12 pages

Class and Object

The document explains the concepts of classes and objects in Java, detailing their definitions, syntax, and examples. It also covers constructors, including types and differences from methods, as well as local and instance variables, and the use of the 'this' keyword. Additionally, it discusses encapsulation, its importance, and how to implement it in Java for data security and control.

Uploaded by

sagarbabail18
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

Class and Object

1. Class in Java

A class in Java is a blueprint or template used to create objects.


It defines:

 Variables (Data members / Attributes)

 Methods (Functions / Behaviors)

 Constructors

It does not occupy memory until an object is created.

Syntax of a Class

class ClassName {
// data members
// methods
}

2. Object in Java

An object is an instance of a class.


It represents a real-world entity and occupies memory.

An object contains:

 State (variables)

 Behavior (methods)

Syntax to Create an Object

ClassName obj = new ClassName();

3. Example: Class and Object in Java

Example Program

class Student {
// Data members
String name;
int rollNo;

// Method
void display() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNo);
}
}

public class Main {


public static void main(String[] args) {

// Creating object
Student s1 = new Student();

// Assigning values
[Link] = "Rahul";
[Link] = 101;

// Calling method
[Link]();
}
}

Output:

Name: Rahul
Roll No: 101

Constructor
1. Definition

A constructor in Java is a special method that is used to initialize objects.


It is automatically called when an object is created.

Key Points:

 Constructor name must be the same as the class name.

 It does not have a return type (not even void).

 It is executed when the object is created using the new keyword.

2. Syntax of Constructor

class ClassName {
ClassName() {
// initialization code
}
}

3. Types of Constructors

1. Default Constructor (No-Argument Constructor)

A constructor that does not take any parameters.

Example:

class Student {
String name;

Student() {
name = "Unknown";
}

void display() {
[Link]("Name: " + name);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
[Link]();
}
}

Output:

Name: Unknown

2. Parameterized Constructor

A constructor that accepts arguments to initialize variables.

Example:

class Student {
String name;
int roll;
Student(String n, int r) {
name = n;
roll = r;
}

void display() {
[Link]("Name: " + name);
[Link]("Roll: " + roll);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student("Rahul", 101);
[Link]();
}
}

Output:

Name: Rahul
Roll: 101

3. Copy Constructor (User-Defined)

Java does not provide a built-in copy constructor like C++, but we can create one manually.

Example:

class Student {
String name;
int roll;

Student(String n, int r) {
name = n;
roll = r;
}

// Copy constructor
Student(Student s) {
name = [Link];
roll = [Link];
}

void display() {
[Link](name + " " + roll);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student("Amit", 102);
Student s2 = new Student(s1);
[Link]();
}
}

4. Constructor vs Method

Basis Constructor Method

Name Same as class Any name

Return Type No return type Must have return type

Purpose Initialize object Perform action

Invocation Called automatically Called explicitly

5. Important Concepts Related to Constructors

1. Constructor Overloading

Multiple constructors in the same class with different parameters.

Example:

class Demo {
Demo() {
[Link]("Default Constructor");
}

Demo(int x) {
[Link]("Parameterized Constructor: " + x);
}
}
2. this Keyword in Constructor

Used to refer to current object or call another constructor.

class Demo {
int x;

Demo(int x) {
this.x = x; // differentiates instance variable
}
}

Local Variable

Definition:

A local variable is a variable declared inside a method, constructor, or block.


It can only be accessed within that method or block.

Key Features:

 Declared inside a method/constructor/block.

 Scope limited to that method/block.

 Must be initialized before use.

 Stored in stack memory.

 Cannot use access modifiers (public, private, etc.).

Example:

class Demo {
void show() {
int x = 10; // Local variable
[Link]("Value of x: " + x);
}
}

Here:

 x is a local variable.

 It exists only inside the show() method.


2. Instance Variable

Definition:

An instance variable is declared inside a class but outside any method, constructor, or block.
Each object has its own copy of instance variables.

Key Features:

 Declared inside class, outside methods.

 Scope is throughout the class.

 Default values are assigned by Java.

 Stored in heap memory.

 Can use access modifiers.

Example:

class Student {
String name; // Instance variable
int roll; // Instance variable

void display() {
[Link](name + " " + roll);
}
}

Here:

 name and roll are instance variables.

 Each object of Student will have separate values.

3. Combined Example

class Student {
String name; // Instance variable

void setName(String n) {
name = n;
int temp = 100; // Local variable
[Link]("Temp value: " + temp);
}
}

Here:
 name → Instance variable

 temp → Local variable

4. Difference Between Local and Instance Variable

Basis Local Variable Instance Variable

Declaration Inside method/block Inside class, outside methods

Scope Limited to method Entire class

Memory Stack Heap

Default Value No default value Gets default value

Access Modifiers Not allowed Allowed

Lifetime Until method ends As long as object exists

5. Default Values of Instance Variables

Data Type Default Value

int 0

double 0.0

boolean false

String null

Local variables must be initialized before use.

This Keyword in Java

Definition

The this keyword in Java is a reference variable that refers to the current object of the class.

It is mainly used to differentiate between instance variables and local variables when they
have the same name.

Why We Use this


When a local variable and instance variable have the same name, Java gets confused.
this helps to refer to the instance variable of the current object.

Common Uses of this Keyword

1️⃣ To Refer Instance Variables

When local variable and instance variable have the same name.

Example:

class Student {
String name;

Student(String name) {
[Link] = name; // instance variable = local variable
}

void display() {
[Link]("Name: " + name);
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student("Rahul");
[Link]();
}
}

Output:

Name: Rahul

Encapsulation in Java

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP).


It refers to binding (wrapping) data (variables) and methods (functions) together into a
single unit (class) and restricting direct access to some components of the object.

In simple words:
👉 Encapsulation = Data Hiding + Data Binding
🔹 Definition

Encapsulation is the technique of:

 Declaring variables as private

 Providing public getter and setter methods to access and modify the data

🔹 Why Encapsulation is Important?

1. ✔ Data Security (Protects data from unauthorized access)

2. ✔ Control over data (Validation before updating values)

3. ✔ Improves maintainability

4. ✔ Supports modular programming

5. ✔ Helps achieve abstraction

🔹 How to Achieve Encapsulation in Java?

1. Declare variables as private

2. Provide public getter and setter methods

3. Use object to access methods

🔹 Example of Encapsulation in Java

class Student {
// Private variables (Data hiding)
private String name;
private int age;

// Public setter method


public void setName(String name) {
[Link] = name;
}

// Public getter method


public String getName() {
return name;
}

// Setter with validation


public void setAge(int age) {
if(age > 0) {
[Link] = age;
}
}

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

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
[Link]("RAM");
[Link](20);

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


[Link]("Age: " + [Link]());
}
}

🔹 What Happens Here?

 name and age cannot be accessed directly.

 They can only be accessed through public methods.

 Age is validated before setting the value.

🔹 Without Encapsulation (Wrong Way)

class Student {
public String name;
public int age;
}
❌ Anyone can change data directly
❌ No validation
❌ Data security risk

🔹 Real-Life Example

Think of a Bank Account:

 You cannot directly access the balance.

 You must use methods like deposit() or withdraw().

 Bank controls how the balance is updated.

You might also like