OOPs - Object - Class - Encapsulation
OOPs - Object - Class - Encapsulation
DATE : 25.09.2024
Contents
• Encapsulation
Objects: Recap
• It represents the real-life entities. Example: pen, chair, table, computer, watch, etc.,
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
Class: Recap
• 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.
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
Class Declaration
Access Modifiers
• Access modifiers or specifiers defines the scope and accessibility of data and method in class.
2. protected: accessible within the class in which it is defined and in its subclass(es).
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
Access Modifier Within Class Within Package Outside package Outside package
by subclass only
Private Yes No No No
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.
Syntax:
• The new keyword creates (instantiates) a new instance. It instantiates a class by allocating memory
for a new object.
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.
• 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();
}
}
}
• 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
Array of Objects:
• Like array of primitive types, the array of objects to store the location of reference variables of the
object.
} Employee id : 1002
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
/* 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("--------------------------");
}
} 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
} --------------------------------------------
}
}
Constructors
object is created. It is used to initialize the object and give initial values for object attributes.
• Constructor cannot be abstract, static, final, and synchronized. (Will discuss Later)
Constructors
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.
/**
* This example demonstrates compiler defined default constructor.
*/
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);
}
}
Output
The default Initial value of employee id is: 0
The default Initial value of employee name is: null
/**
* This example demonstrates user defined default constructor.
*/
Employee() {
empId=1111; //Initial value of employee id
empName=“AAA-BBB”; //Initial value of employee name
}
}
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
/* 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("--------------------------");
}
} --------------------------
Parameterized Constructor
constructors.
/**
* This example demonstrates parameterized constructor.
*/
//Parameterized constructor
Employee(int id, String name){
empId=id; //Assign Initial employee id
empName=name; //Assign Initial employee name
}
}
/* 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("--------------------------");
}
} --------------------------
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:
• They are differentiated by the Java compiler by the number of arguments, order of arguments listed
and the types of each arguments.
/**
* 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
}
/* 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;
}
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
• 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
Garbage Collection
• System. gc() forces the garbage collector to run, while the finalize() method of your object defines
Output
Object is destroyed by the Garbage Collector
Inside the main() method
‘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
Note:
• this keyword cannot be used outside a class
/**
* This example illustrates the problem
* if we dont use ‘this’ keyword.
*/
//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
/**
* 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
//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
/** 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
}
System.out.println("--------------------------"); --------------------------
}
public static void main(String[] args) {
Theatre T = new Theatre();
T.setTheatreDetails(“T4523”, "INOX");
T.getTheatreDetails();
}
}
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 before any objects of its class are created.
Static Block
Static Variable
• 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
/**
* 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
Output
Static Block 1
Static Block 2
Employee Id : 1002
Employee Name : Peter
/**
* This example demonstrates 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
Static Methods
• A static method belongs to the class and common for all the object of a class.
Restrictions:
/**
* This example demonstrates static method.
*/
Introduction
• 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
Introduction
• 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
Setter and getter Method: It is used to update and retrieve the value of variables.
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.
Example
/**
* This example demonstrates encapsulation features using getter and setter methods
*/
Example
Example
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}
Example
Quiz
a) This b) static
c) volatile d) public
b) static
Quiz
Quiz
a) Encapsulation b) Abstraction
c) Polymorphism d) Inheritance
a) Encapsulation
Quiz
a) protected b) private
c) public d) default
c) public
Quiz
a) Trainee t; b) Trainee()
Quiz
c) public Person()
Quiz
a) this b) reference
c) static d) public
a) this
Quiz
a) class b) java
c) new d) create
c) new
Quiz
a) 1 b) 2
c) 3 d) Any number
a) 1
Quiz
a) 32 b) 64