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

OOPs - Object - Class - Encapsulation

basics of Object oriented programming

Uploaded by

suvetha309
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)
16 views

OOPs - Object - Class - Encapsulation

basics of Object oriented programming

Uploaded by

suvetha309
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
You are on page 1/ 89

SDE Readiness Training

Empowering Tomorrow’s Innovators


Module I
Java Software Development:
Effective Problem Solving

2 Collections in Java | © SmartCliff | Internal | Version 1.0


Object Oriented Programming
(OOP) Concepts
Learning Level : Basics

DATE : 25.09.2024
Contents

• Classes and Objects

• Encapsulation

4 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

5 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Objects: Recap

• Object is the primary unit of Object-Oriented Programming.

• It represents the real-life entities. Example: pen, chair, table, computer, watch, etc.,

• It can be physical or logical.

• An object has three characteristics:

1. State: represents data or value stored in an object.

2. Behavior: represents the behavior or functionality of an object. This function is used to manipulate
the data and interact with other objects

3. Identity: It gives unique name to an object. Each object is identified in Java by unique memory
location.
6 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Objects

State: colour, size, weight, brand State: Name, colour, Breed, Type State: Name, black hair, black eyes,
heighht
Behaviour: Barking, Fetching,
Behaviour: Change channel, Behaviour: eat, study, play, sleep
Wagging the tail
Manage Volume

7 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Class: Recap

• Class is a template or blueprint of the objects.

• It defines the state (variables) and behaviour (methods) common to all objects of a certain kind.

• A class is a logical entity and describes the object's properties and behaviours.

• It is used to create object instances.

8 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Object Oriented Programming
Object and Class - Recap Objects
Color: Silver
A silver Hyundai car
Transmission: Manual
with manual gear,
Brand: Hyundai
Class – Car diesel fuel type, and
Mileage: 45, 000 kms
45,000 kms mileage.
States Fuel Type: Diesel

Color
Color: Red A red Audi with
Transmission Transmission: Automatic automatic gear,
Brand Brand: Audi 47,500 kms mileage,
Mileage: 47, 500 kms and electric fuel
Mileage
Fuel Type: Electric type.
Fuel Type

Behaviors Color: Orange An orange Tata car


Transmission: Manual with manual
Accelerate Brand: Tata transmission, petrol
Reverse Mileage: 35, 800 kms fuel type, and
Fuel Type: Petrol 35,800 kms mileage.
Park
9 Object Oriented Programming (OOP)| © SmartCliff | Internal | Version 1.0
Object Oriented Programming

Object – Instance of a class - Recap


Instances of Car class
Color: Silver
Transmission: Manual Car 1
States
Brand: Hyundai
Mileage: 45, 000 kms
Color:

Fuel Type: Diesel Transmission:


Brand:
Color: Red
Transmission: Automatic Mileage:
Brand: Audi Car 2 Fuel Type:
Mileage: 47, 500 kms Behaviors
Fuel Type: Electric
Acceleration()
Color: Orange
Reversing()
Transmission: Manual
Park()
Brand: Tata
Mileage: 35, 800 kms CAR
Car 3
Fuel Type: Petrol

10 Object Oriented Programming (OOP)| © SmartCliff | Internal | Version 1.0


Classes and Objects

Class Declaration

Syntax: Keyword Example:


Class Declaration

Access specifier class Class_name{


Fields public class Theatre {
+ String theatreID = “T4523”; Fields/
Properties / Attributes/
Behaviours String theatreName = "INOX"; States

} public void displayTheatre(){


System.out.println("Theatre ID : "+theatreID);
Operations/
System.out.println("Theatre Name : "+theatreName); Behaviours/
Methods
}
}

11 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Access Modifiers

• Access modifiers or specifiers defines the scope and accessibility of data and method in class.

• There are three Java access modifiers:

1. public: accessible in all class in your application.

2. protected: accessible within the class in which it is defined and in its subclass(es).

3. private: accessible only within the class in which it is defined.

4. default (declared/defined without using any modifier) : accessible within same class and package
within which its class is defined.

Note:
• For classes and interface, you can use either public or default

• For attributes, methods and constructors, you can use the one of the following: Private, Protected, Public

12 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Access Modifiers: In a Nutshell

Access Modifier Within Class Within Package Outside package Outside package
by subclass only

Public Yes Yes Yes Yes

Private Yes No No No

Protected Yes Yes Yes No

Default Yes Yes No No

13 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Object Creation

• When an object of a class is created, the class is said to be instantiated. All the instances can have the
same attributes and the functions of the class.

• The memory allocation of each object is unique , which means the value initialized to each object is
distinct.

• A single class may have any number of instances.

Syntax:

ClassName objectName = new ClassName();

• The new keyword creates (instantiates) a new instance. It instantiates a class by allocating memory
for a new object.

14 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Object Creation

/* This Example demonstrates how to create the Object for Theatre class */ public static void main(String[] args) {
public class Theatre { //Declare and instantiate
String theatreID = “T4523”; Theatre T1 = new Theatre();
String theatreName = "INOX"; //Declare the reference
public void getTheatreDetails(){ //Displaying Theatre details Theatre T2;
System.out.println("Theatre ID : "+theatreID); //Then instantiate
System.out.println("Theatre Name : "+theatreName); T2 = new Theatre();
} }
}

Note:
• A declaration only create reference variable.
• Allocate memory to object only at that time of instantiation.

15 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Accessing Class Members

• After creation of object to access class members using dot operator (.)

/* This Example demonstrates how to create the Object for Theatre class */ public static void main(String[] args) {
public class Theatre { //Declare and instantiate
String theatreID; Theatre T1 = new Theatre();
String theatreName = "INOX"; //Fields are accessed
public void getTheatreDetails(){ //Displaying Theatre details T1.theatreID = “T4523”;
System.out.println("Theatre ID : "+theatreID); //Methods are called
System.out.println("Theatre Name : "+theatreName); T1.getTheatreDetails();
}
}
}

16 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Accessing Class Members: Example #1

/**This Example demonstrates how to access class members using object. */


public class Employee {//Create Employee class
int empId;
String empName;

void setEmployeeDetail(int id,String name) {


empId = id;
empName = name;
}
void getEmployeeDetail () {
System.out.println("Employee id : "+empId);
System.out.println("Employee name : "+empName);
}
}
17 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Accessing Class Members: Example #1


public class EmployeeMain {
public static void main(String[] args) {
Employee Emp1 = new Employee(); //First Object Creation
Employee Emp2 = new Employee(); //Second Object Creation
Emp1.setEmployeeDetail(1001, "RAM");
Emp2.setEmployeeDetail(1002, "RAJ");
Emp1.getEmployeeDetail();
Emp2.getEmployeeDetail();
}
}
Output
Employee id : 1001
Employee name : RAM
Employee id : 1002
Employee name : RAJ
18 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Accessing Class Members: Example#2


/* This Example demonstrates how to access class members of Theatre Class*/
public class Theatre {
String theatreID;
String theatreName;
public void setTheatreDetails(String id, String name) {
theatreID = id;
theatreName = name;
}
public void getTheatreDetails(){
System.out.println("------Theatre Detail------");
System.out.println("Theatre ID : "+theatreID);
System.out.println("Theatre Name : "+theatreName);
System.out.println("--------------------------");
}
19 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Accessing Class Members: Example#2


public static void main(String[] args) { Output

Theatre T = new Theatre(); ------Theatre Detail------

T.setTheatreDetails(“T4523”, "INOX"); Theatre ID : T4523

T.getTheatreDetails(); Theatre Name : INOX


} --------------------------
}

20 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Object Creation: More Details

Multiple Object Creation

• To create multiple objects like multiple variable, declare in the same declaration.

• Example: Theatre T1 = new Theatre(), Theatre T = new Theatre(); //two objects in single creation

Anonymous object

• It means nameless object. An object which has no reference is known as an anonymous object.

• It can be used at the time of object creation only. If you have to use an object only once, an

anonymous object is a good approach.

• Syntax: new className().methodName()

• Example: new Theatre().setTheatreDetails(“T1001”,”INOX”);


21 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Object Creation: More Details

Array of Objects:

• Like array of primitive types, the array of objects to store the location of reference variables of the

object.

• Syntax: Class obj[]= new Class[array_length];

• Example: Theatre obj[]=new Theatre[10]; //Create 10 Objects

22 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Array of Objects: Example #1

/** This example demonstrates the array of objects. */


public class Employee{
int empId;
String empName;
void setEmployeeDetail(int id,String name){
empId = id;
empName = name;
}
void getEmployeeDetail (){
System.out.println("Employee id : "+empId);
System.out.println("Employee name : "+empName);
}
}
23 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Array of Objects: Example #1


public class EmployeeArrayObject { Output

public static void main(String[] args) { -----Employee 1 Detail-----

Employee Emp[] = new Employee[2]; Employee id : 1001

for(int i=0;i<2;i++) { Employee name : AMUDHAN

Emp[i] = new Employee(); -----Employee 2 Detail-----

} Employee id : 1002

System.out.println("-----Employee 1 Detail-----"); Employee name : RAJ

Emp[0].setEmployeeDetail(1001, "AMUDHAN");
Emp[0].getEmployeeDetail();
System.out.println("-----Employee 2 Detail-----");
Emp[1].setEmployeeDetail(1002, "RAJ");
Emp[1].getEmployeeDetail();
}
}
24 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Array of Objects: Example #2

/* This Example demonstrates how to create array of objects for theatre class */
public class Theatre {
String theatreID;
String theatreName;
public void setTheatre(String id, String name) {
theatreID = id;
theatreName = name;
}
public void getTheatreDetails (){
System.out.println("------Theatre Detail------");
System.out.println("Theatre ID : "+theatreID);
System.out.println("Theatre Name : "+theatreName);
System.out.println("--------------------------");
}

25 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Array of Objects: Example #2

public static void main(String[] args) { ------Theatre 1 Detail-----------

Theatre T[] = new Theatre[3]; Theatre ID : T4523

for(int i=0;i<T.length;i++) { Theatre Name : INOX

T[i] = new Theatre(); ------Theatre 2 Detail------

} Theatre ID : T4742
T[0].setTheatre(“T4523”, "INOX"); Theatre Name : SPI Cinemas
T[1].setTheatre(“T4742”, "SPI Cinemas"); ------Theatre 3 Detail------
T[2].setTheatre(“T4965”, "Metro City"); Theatre ID : T4965
for(int i = 0;i<T.length;i++) {
T[i].getTheatreDetail(); Theatre Name : Metro City
} --------------------------------------------
}
}

26 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructors

• In java, Constructor is a special method that is executed automatically whenever an instance of

object is created. It is used to initialize the object and give initial values for object attributes.

Rules for Constructor:

• Constructor has same name as class name.

• Constructor do not have return value but can take arguments.

• Constructor cannot be abstract, static, final, and synchronized. (Will discuss Later)

27 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructors

• There are two types of constructors in Java:

1. No-argument/default constructor

2. Parameterized constructor

Default Constructor

• A constructor that has no parameters is known as default constructor. It is either user defined, or
compiler defined constructor.

• If we don’t create any constructor in a class, then compiler creates default constructor for the class
and assign default values to attributes .

• The user defined default constructor provides user given initial values to attributes of the class for each
instantiation.

28 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Default Constructor: Example #1

/**
* This example demonstrates compiler defined default constructor.
*/

class Employee { //define Employee class


int empId;
String empName;

void getEmployeeDetails () {
System.out.println(“The default Initial value of employee id is: ”+empId);
System.out.println(“The default Initial value of employee name is: ”+empName);
}
}

29 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Default Constructor: Example #1

class EmployeeMain { //Main Class


public static void main (String[] args) {
Employee emp= new Employee();
// Default constructor initialize default values to the objects
emp.getEmployeeDetails();
}
}

Output
The default Initial value of employee id is: 0
The default Initial value of employee name is: null

30 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Default Constructor: Example #2

/**
* This example demonstrates user defined default constructor.
*/

class Employee { //define Employee class


int empId;
String empName;
//User defined default constructor

Employee() {
empId=1111; //Initial value of employee id
empName=“AAA-BBB”; //Initial value of employee name
}
}

31 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Default Constructor: Example #2

Output
void getEmployeeDetails () {
The Initial value of employee id is: 1111
System.out.println(“The Initial value of employee id is: ”+empId);
The Initial value of employee name is: AAA-BBB
System.out.println(“The Initial value of employee name is: ”+empName);
}
}
class EmployeeMain { //Main Class
public static void main (String[] args) {
// this invoke compiler defined default constructor.
Employee emp= new Employee();
// Display assigned initial values
emp.getEmployeeDetails();
}
}
32 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Default Constructor: Example #3

/* This example demonstrates user defined default constructor for the Theatre class */
public class TheatreConstructor {
String theatreID;
String theatreName;
TheatreConstructor(){
theatreID = “T4965”;
theatreName = "Metro City";
}
public void getTheatreDetails (){
System.out.println("------Theatre Detail------");
System.out.println("Theatre ID : "+theatreID);
System.out.println("Theatre Name : "+theatreName);
System.out.println("--------------------------");
}

33 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Default Constructor: Example #3

public static void main(String[] args) { Output

TheatreConstructor T = new TheatreConstructor(); ------Theatre Detail------

T.getTheatreDetail(); Theatre ID : T4965

} Theatre Name : Metro City

} --------------------------

34 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Parameterized Constructor

• A constructor that accepts arguments are known as parameterized constructor.

• It is used to initialize the object with your own values.

• In parameterized constructor, we must provide initial values of objects as arguments to the

constructors.

35 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Parameterized Constructor: Example #1

/**
* This example demonstrates parameterized constructor.
*/

class Employee { //define Employee class


int empId;
String empName;

//Parameterized constructor
Employee(int id, String name){
empId=id; //Assign Initial employee id
empName=name; //Assign Initial employee name
}
}

36 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Parameterized Constructor: Example#1

void getEmployeeDetails (){ Output


System.out.println(“User given initial employee id is: ”+empId); User given Initial value of employee id is: 1003
System.out.println(“User given initial employee name is: ”+empName); User given Initial value of employee name is: Peter
}
}
class EmployeeMain { //Main Class
public static void main (String[] args) {
// Pass arguments to the constructor
Employee emp= new Employee(1003,”Peter”);
//Display employee initial values
emp.getEmployeeDetails();
}
}

37 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Parameterized Constructor: Example#2

/* This example demonstrates user defined Parameterized constructor for the Theatre class */
public class TheatreConstructor {
String theatreID;
String theatreName;
TheatreConstructor(String tid, String tname){
theatreID = tid;
theatreName = tname;
public void getTheatreDetails (){
System.out.println("------Theatre Detail------");
System.out.println("Theatre ID : "+theatreID);
System.out.println("Theatre Name : "+theatreName);
System.out.println("--------------------------");
}

38 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Parameterized Constructor: Example #2

public static void main(String[] args) { Output

TheatreConstructor T = new TheatreConstructor(“T4742”,”SPI Cinemas”); ------Theatre Detail------

T.getTheatreDetails(); Theatre ID : T4742

} Theatre Name : SPI Cinemas

} --------------------------

39 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructor Overloading

• Constructor overloading: More than one constructor with different parameter lists depending on the
application. Each constructors functions in its own distinct way.

• Example:

Employee() { ….} //Default Constructor

Employee(int empId) {…..} //One Parameter Constructor

Employee(String name, String designation) {….} // Two parameter Constructor

• They are differentiated by the Java compiler by the number of arguments, order of arguments listed
and the types of each arguments.

40 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructor Overloading: Example #1

/**
* This example demonstrates the constructor overloading */
class Employee { //define Employee class
int empId;
String empName;
Employee(){ //Default Constructor
empId=1111;
empName="AAA-BBB";
}
Employee(int id, String name){ //Parameterized constructor
empId=id; //Assign Initial employee id
empName=name; //Assign Initial employee name
}

41 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructor Overloading: Example #1

void getEmployeeDetails (){ Output


System.out.println(“Employee id is: "+empId); Employee id : 1111
System.out.println(“Employee name is:"+empName); Employee name :AAA-BBB
} Employee id : 1001
} Employee name :Peter
class EmployeeMain { //Main Class
public static void main (String[] args) {
Employee emp0=new Employee(); //Default Constructor
Employee emp1= new Employee(1001,“Peter"); //Parameterized Constructor
//Display employee initial values
emp0.getEmployeeDetails();
emp1.getEmployeeDetails();
}
}
42 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Constructor Overloading: Example #2

/* This example demonstrates user defined constructor overloading for the Theatre class */
public class TheatreConstructor {
String theatreID;
String theatreName;
TheatreConstructor(){
theatreID = “T4965”;
theatreName = "Metro City";
}
TheatreConstructor(String tid, String tname){
theatreID = tid;
theatreName = tname;
}

43 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Constructor Overloading: Example #2

public void getTheatreDetails(){ Output

System.out.println("------Theatre Detail------"); Default Constructor


------Theatre Detail------
System.out.println("Theatre ID : "+theatreID);
Theatre ID : T4965
System.out.println("Theatre Name : "+theatreName);
Theatre Name : Metro City
System.out.println("--------------------------");
--------------------------
}
Parameterized Constructor
public static void main(String[] args) {
------Theatre Detail------
TheatreConstructor T1 = new TheatreConstructor();
Theatre ID : T4742
TheatreConstructor T2 = new TheatreConstructor(“T4742”, "SPI Cinemas"); Theatre Name : SPI Cinemas
System.out.println("Default Constructor"); --------------------------
T1. getTheatreDetails();
System.out.println("Parameterized Constructor");
T2. getTheatreDetails();
}
44 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Garbage Collection

• The allocated memory during object invocation should be released at the end of the program to reuse

that memory for some other object. In C++, the programmers handle this memory management

explicitly using destructor.

• In Java no explicit destructor is required like C++ because it provides the automatic garbage

collector.

• Both the garbage collector and destructor are used for releasing memory.

• The finalize() method of Object class is a method that the Garbage Collector always calls just before

the destroying the object to perform clean-up activity.

45 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Garbage Collection

• System.gc() method requesting JVM to run garbage collector.

finalize() vs. gc()

• System. gc() forces the garbage collector to run, while the finalize() method of your object defines

what garbage collector should do when collecting this specific object.

46 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Garbage Collection: Example

/*** This example demonstrates the garbage collection*/


public class GarbageCollector{
public static void main(String[] args){
GarbageCollector obj = new GarbageCollector();
obj.finalize();
System.gc(); // requesting JVM for running Garbage Collector
System.out.println("Inside the main() method");
}
@Override
protected void finalize() {
System.out.println("Object is destroyed by the Garbage Collector");
}
}

Output
Object is destroyed by the Garbage Collector
Inside the main() method

47 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword

• ‘this’ is a reference variable that refers to the current object.

Usage of ‘this’ Keyword

• It can be used to refer instance variable of current class and return the current class instance.

• It can be used to invoke or initiate current class constructor. It means constructor chaining is

possible. For example, Call default constructor from parameterized constructor.

• It resolves the ambiguity problem between local and instance variable.

Note:
• this keyword cannot be used outside a class

48 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword :Example #1

/**
* This example illustrates the problem
* if we dont use ‘this’ keyword.
*/

public class Employee { Note:


int empId; // instance variable
• ‘this’ keyword resolves the ambiguity
String empName; //instance variable
Employee(String empName, int empId ) { between instance and local variable.
Both local
empName = empName; • This example illustrates the problem, if
and instance
empId = empId;
variables are we don't use ‘this’ keyword.
} same
void display() {
System.out.println(“Emp name: ”+empName+ “ \tEmpID: "+ empId);
}
}

49 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword :Example #1

//Main Class
class EmployeeMain {
public static void main (String[] args) {
Employee emp = new Employee("Manas Kumar",29);
emp.display();
}
}

Output
Emp name: null EmpID: 0

50 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword :Example #2

/**
* This program illustrates the use of ‘this’ keyword.
*/
public class Employee { Note:
int empId;
• ‘this’ keyword resolves the ambiguity
String empName;
between instance and local variables.
Employee(String empName, int empId ) {
this.empName = empName; Here this.empId
this.empId = empId; and empName are
instance variables
}
void display() {
System.out.println(name+ " \t"+ empId);
}
}
51 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

‘this’ Keyword :Example #2

//Main Class
class EmployeeMain {
public static void main (String[] args) {
Employee emp = new Employee("Manas Kumar",29);
emp.display();
}
}

Output
Employee id : 29
Employee name : Manas Kumar

52 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword :Example #3

/** This program illustrates the use of ‘this’ keyword in Theatre Class **/
public class Theatre {
String theatreID;
String theatreName;
public void setTheatreDetails(String theatreID, String theatreName){
this.theatreID = theatreID; //this.theatreId and theatreId are instance variable
this.theatreName = theatreName; //this.theatreName and theatreName are instance variable
}

53 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

‘this’ Keyword :Example #3

public void getTheatreDetails() { Output

System.out.println("------Theatre Detail------"); ------Theatre Detail------

System.out.println("Theatre ID : "+theatreID); Theatre ID : T4523

System.out.println("Theatre Name : "+theatreName); Theatre Name : INOX

System.out.println("--------------------------"); --------------------------

}
public static void main(String[] args) {
Theatre T = new Theatre();
T.setTheatreDetails(“T4523”, "INOX");
T.getTheatreDetails();
}
}

54 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Members

• The static keyword in Java is used for managing memory efficiently with the class instances.

• We can apply static keyword with variables, methods, blocks and nested classes.

• The static keyword belongs to the class rather than each instance of the class. The static member is

common to the class and it is same for all the instances created for that class. For example, the

company name of employees, college name of students, bank name of account holders, etc.

• Static members can be accessed without objects of a class.

• Static members can be accessed before any objects of its class are created.

55 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Block and Static Variables

Static Block

• Static block mainly used for to initialize the static variables.

• It is executed at the time of class is loaded in the memory.

• In case of multiple static blocks, it will execute in the same order.

Static Variable

• Static variable also called as class variable.

• It is common to all the instance of the class.

• Memory allocation for static variables are happens when the class is loaded in the memory.
56 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Static Members : Static Block

/**
* This example demonstrates static block */
class Employee{ //Main Class
static int empId;
static String empName;
static{
System.out.println("Static Block 1");
empId = 1001;
empName = "Alex";
}
static{
System.out.println("Static Block 2");
empId = 1002;
empName = "Peter";
}
57 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Static Members : Static Block

public static void main(String args[]) Note:


{
System.out.println("Employee Id : "+empId); • ‘static block’ is used to initialize the static data
System.out.println("Employee Name : "+empName); member.
}
• It is executed only once when the class gets
}
loaded.

Output
Static Block 1
Static Block 2
Employee Id : 1002
Employee Name : Peter

58 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Members : Static Variable

/**
* This example demonstrates static variable.
*/

class Employee { //define Employee class


int empId;
String empName;
static String companyName=“ABC Solutions”; //static variable
//Parameterized constructor
Employee(int id, String name) {
empId=id; //Assign Initial employee id
empName=name; //Assign Initial employee name
}
}

59 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Members : Static Variable

void display (){ //Employee Details Note:


System.out.println(“Company Name : ”+companyName); //common to all employee • Here, companyName Static
System.out.println(“Employee Id : ”+empId); variable is common for all
System.out.println(“Employee Name : ”+empName);
objects created for that class.
}}
• All instances of the class
class EmployeeMain {//Main Class
share the same static variable.
public static void main (String[] args) {
static block and static
// Pass arguments to the constructor
variables are executed in
Employee emp1= new Employee(1001,”Ram Kumar”);
order they are present in the
Employee emp2= new Employee(1002,”Raj Kumar”);
program
//Display employee details
emp1.display();
emp2.display();
}}
60 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Static Members : Static Variable

Output
Company Name : ABC Solutions
Employee Id : 1001
Employee Name : Ram Kumar
Company Name : ABC Solutions
Employee Id : 1002
Employee Name : Raj Kumar

61 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Methods

• A static method belongs to the class and common for all the object of a class.

• It can be invoked without object of class or using class name.

Restrictions:

• Can access only other static methods and variables.

• Cannot refer to this or super keyword.

62 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Methods : Example

/**
* This example demonstrates static method.
*/

class Employee { //define Employee class


int empId;
String empName;
static String companyName = “ABC Solutions”; //static variable
//Parameterized constructor
Employee(int id, String name){
empId = id; //Assign Initial employee id
empName = name; //Assign Initial employee name
}
}

63 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Methods : Example

//Change company name


static void getCompany(){
companyName = “XYZ Private Ltd”; //Access static data
}
//Display Employee Details
void display (){
System.out.println(“Company Name : ”+companyName); //common to all employee
System.out.println(“Employee Id : ”+empId);
System.out.println(“Employee Name : ”+empName);
}
}

64 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Static Methods : Example

class EmployeeMain {//Main Class Output


public static void main (String[] args) { Company Name : ABC Solutions
// Pass arguments to the constructor Employee Id : 1001
Employee emp1= new Employee(1001,”Ram Kumar”); Employee Name : Ram Kumar
Employee emp2= new Employee(1002,”Raj Kumar”); Company Name : ABC Solutions
//Display employee details Employee Id : 1002
emp1.display(); Employee Name : Raj Kumar
emp2.display();
Company Name : XYZ Private Ltd
Employee.getCompany(); //Access static method
Employee Id : 1001
//Display employee details after change company
Employee Name : Ram Kumar
emp1.display();
Company Name : XYZ Private Ltd
emp2.display();
Employee Id : 1002
}
Employee Name : Raj Kumar
}
65 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Static Members : Static Method


/ * This example demonstrates static members created for the Theatre class */
public class Theatre {
static int theatreCount = 0; //static variable
String theatreID;
String theatreName;
Theatre(String tid,String name){
theatreID = tid;
theatreName = name;
theatreID++;
}
public void DisplayTheatre() {
System.out.println(“Theatre ID : "+theatreID);
System.out.println(“Theatre Name : "+theatreName);
System.out.println(“Total Number of theatres: "+theatreCount);
}
66 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Classes and Objects

Static Members : Static Method

public static void main(String args[]) { Output


System.out.println(“Theatre Detail"); Theatre Detail
Theatre T1 = new Theatre(“T5432”,”SPICINEMAS); Theatre ID : T5432
Theatre T2 = new Theatre(“T2346”,”INOX”); Theatre Name : SPICINEMAS
T2.DisplayTheatre(); Total Number of theatres : 1
}
} Theatre Detail
Theatre ID : T2346
Theatre Name : INOX
Total Number of theatres : 2

67 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Encapsulation

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

68 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Encapsulation

Introduction

• Encapsulation is a another important concept of Object Oriented Programming.

• It is the process of binding the data and behaviour into a single unit called class.

Need of Encapsulation:

• In this world, many data are sensitive, confidential and personal. Hence privacy is an important threat

with respect to every data.

• Data privacy is achieved with the help of encapsulation concept in Java.

69 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Encapsulation

Introduction

Achieve encapsulation in Java:

• Encapsulation can be achieved by declaring data in the class members as private.

• Provide public setter and getter methods to modify and view the private class members. (Good

Practice)

Note:

• Encapsulation prevents the private class members being accessed by external classes and

methods. Therefore, it is also known as data hiding.

70 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Encapsulation

Setter and getter Methods

Setter and getter Method: It is used to update and retrieve the value of variables.

Rules for setter Method:

• It should be public, if it needs to be accessed from outside.

• The return-type should be void.

• The setter method should be prefixed with set.

• It should take some argument i.e. it should not be no-argument method.

Rules for getter Method:


• It should be public, if it needs to be accessed from outside
• The return-type should not be void i.e. according to our requirement we have to give return-type.
• The getter method should be prefixed with get.
• It should not take any argument.
71 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0
Encapsulation

Advantages

• Use only a setter or getter method, you implicitly achieve member of the class that becomes read-only
or write-only option.

• It gives you command over the data. For Example, You can write the logic inside the setter method if
you need to set the value of empId based on some criteria.

• It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.

• The encapsulate class is easy to test. So, it is better for unit testing.

• The standard IDE's are providing the facility to generate the getters and setters method it helps to
create encapsulate class easy and fast.

72 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Example

/**
* This example demonstrates encapsulation features using getter and setter methods
*/

class Employee { //define Employee class


//private data members
private int _empId;
private String _empName;
//public getter and setter methods
//Set employee id
public void setId(int id) {
_empId=id;
}
}

73 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Example

//Set employee name


public void setName(String name) {
_empName=name;
}
//Get employee id
public int getId() {
return _empId;
}
//Get employee name
public String getName(){
return _empName;
}
}

74 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Example

class EmployeeMain { //Main Class Output


public static void main (String[] args) { Employee Id : 1001
Employee emp= new Employee(); //create instance of Employee class Employee Name Ram Kumar
//setting values through setter methods
emp.setId(1001);
emp.setName(“Ram Kumar”);
//getting values through getter methods
System.out.println(“Employee Id: “+getId());
System.out.println(“Employee Name: “+getName());
}
}

75 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Example
/*This example demonstrates encapsulation features using getter and setter methods */
public class Theatre {
private static int theatreCount = 0;
private String theatreID;
private String theatreName;
public void setTheatreID(String id) { theatreID = id; }
public void setTheatreName(String name) { theatreName = name;}
public String getTheatreId() {return theatreID;}
public String getTheatreName() {return theatreName}

76 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


Classes and Objects

Example

public static void main(String[] args) { Output


Theatre theatre = new Theatre(); --------Theatre Detail----------
theatre.setTheatreID(“T1002”); Theatre ID : T1002
theatre.setTheatreName("INOX"); Theatre Name : INOX
System.out.println("--------Theatre Detail----------");
System.out.println("Theatre ID : "+theatre.getTheatreID());
System.out.println("Theatre Name : "+theatre.getTheatreName());
}
}

77 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

1. X is a keyword that denotes member variable or method can


be accessed, without requiring an instantiation of the class
to which it belongs. X is ____

a) This b) static

c) volatile d) public

e) None of the above

b) static

78 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

2. In case the programmer does not provide a constructor for a

class, Java compiler will

a) Throw error b)Create Default constructor

c) Throw run time


d) Create new object
exception

e) None of the above

b) Create Default constructor

79 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

3. ______ provides objects with the ability to hide their internal


characteristics and behaviour.

a) Encapsulation b) Abstraction

c) Polymorphism d) Inheritance

e) None of the above

a) Encapsulation

80 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

4. In a class, an attribute needs to be accessed from any class


in that application. What should be the access specifiers for
that attribute

a) protected b) private

c) public d) default

e) None of the above

c) public

81 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

5. Given a class with the name Trainee. Which of the following


instantiates an object for this class?

a) Trainee t; b) Trainee()

c) Trainee t=new Trainee() d) All the options

e) None of the above

c) Trainee t=new Trainee()

82 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

6. Assume, a class Person. Identify the correct signature for


the constructor

a) void Person() b) private void Person()

c) public Person() d) public void Person()

e) None of the above

c) public Person()

83 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

7. Which of the following keywords acts as a reference variable


to the current object?

a) this b) reference

c) static d) public

e) None of the above

a) this

84 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

8. The keyword used to create a new object in Java is ___.

a) class b) java

c) new d) create

e) None of the above

c) new

85 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

9. In a .java file, how many numbers of public class allowed?

a) 1 b) 2

c) 3 d) Any number

a) 1

86 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


OOP Concepts

Quiz

10. How many maximum numbers of objects can be created


from a single Class in Java?

a) 32 b) 64

c) 256 d) None of these Above

d) None of these Above

87 Object Oriented Programming(OOP) Concepts | © SmartCliff | Internal | Version 1.0


The struggle you’re in today
is developing the strength
you need for tomorrow.
- Robert Tew

88 Collections in Java | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like