Unit 5 Object Oriented Programming-1
Unit 5 Object Oriented Programming-1
• Object Creation: Objects are created from classes using the new keyword, The process of
creating an object is called Instantiation.
• Behavior (Methods): Behavior in Java objects is defined by methods. Methods are functions
associated with objects that operate on the object's state. They can modify the state, perform
actions, or return values.
Ex.
public class Employee
{
public static void main (String[] args)
{
Employee emp1 = new Employee(); // Instantiation.
System.out.println(emp1);
System.out.println(emp1.name);
System.out.println(emp1.eid);
}
}
• Reference: Each object in Java has a unique identity (address in memory). When an object
is assigned to a variable or passed as an argument to a method, only its reference is copied,
not the object itself. Multiple variables can point to the same object (aliasing).
Ex.
• New:
1. New is a keyword.
2. New keyword is used to create the object inside the heap area during execution of the program.
4. Once the object is created inside the heap area then the reference is return to the caller method.
• Constructor:
1. Constructor is special type of method which name is same as the class name.
2. Once the object got created inside the heap area then constructor loads all the non-static member
of the class into the object.
Class
They serve as blueprints or templates for creating objects, which are instances of the class.
Each class encapsulates data (attributes) and behavior (methods) that define the characteristics
and actions of objects belonging to that class. If we want to create the object, before we need
to create the class. All class name in java are non-primitive data types. We can create any
number of object for the class.
• Class Declaration: A class is defined using the class keyword followed by the class name.
It typically starts with an uppercase letter and follows Java naming conventions.
• Terminology:
1. Public: The method is accessible by all classes when we use public specifier.
2. Private: The method is accessible within the same class in which it’s define.
3. Protected: The method is accessible within the same sub class in a different super class.
4. Default: If we do not use any access modifier or specifier in the method declaration java
used “Default” access modifier by default it is visible from same class only.
• Modifier: Modifier is used to change the characteristics of a member
• ReturnType: The method is after execution will return some data back to the caller. In
order to return the some data from the method we need to specified what type of data has
to returned. We can specified the data type by making use of return type. If the method is
does not return anything then we need to use ‘void’ keyword.
3. If the method is does not return anything then we need to use ‘void’ keyword.
• Method Name: The name give to the method is known as method name. Method name
always follow the conventions
1. Single Word: If the method name has to be in a single word then represent all the letters
in lower case.
2. Multi Word: If it is multi word then we can represent the starting word is in lower case
and the next word is in upper case. This is also called as Camel Conventions.
Ex.
Note: A method will get executed only when its called. We can call the method using Method
Call Statement.
• Method Called Flow:
1. When the java program compile and executed, during the execution of a program our JRE
will call only the main() method for execution.
2. When JRE calls main() method for execution it provides the control to the main() method.
3. Now the main() method start the executing whenever the control reaches to the method
called statement, the execution of caller method paused and control is immediately
transferred to called method.
4. Ones the execution of called method is done then control is immediately transferred to the
caller. Now the caller method continuous it execution.
1. Caller Method: The method is which is calling another method is known as calling
method.
2. Called Method: The method which being call by some other method is known as called
method.
Note:
1. For method declaration access modifier, modifier and formal argument are optional.
3. If you don’t specify the formal argument then it becomes no argument method.
• Purpose of Main Method
• Types of Methods
1. No Argument Method
2. Parameterised Method
1. No-Argument Method:
The method does not contain any formal argument this method is known as no
argument method.
Ex.
public static void test ()
{
// Statements;
}
2. Parameterized Method:
Those method accepts formal argument this method is known as Parameterised
Method. Parameterised method are used to accepts data from method called statement.
Ex.
public static void test ( int b )
{
// Statements;
}
• Rules to called Parameterised Method:
2. The type of formal argument and actual argument are both matched if not so our compiler
tries to perform type casting or type promotion
• Formal Argument:
The variable which are declared inside method declaration statement this argument is known
as formal argument
• Actual Argument:
Actual argument which are passed in method called statement is known as Actual Argument.
Ex. No Argument Method
Return Statement: The method after execution will return a data back to the caller (Main
Method) with the help of return keyword.
Return: Return is a keyword and it is control transferred statement. When the control reaches
return keyword immediately the control will be transport to the caller along with data.
Ex.
public class ReturnType
{
public static void main(String[] args)
{
int res = add(10, 20);//Method Call Statement
System.out.println(res);
}
public static int add(int a, int b)// Called method
{
int c = a+b;
return c;
}
}
Ex.
public class ReturnType
{
}
• Static And Static Member:
2. If any member of the classes is prefix with static keyword then it’s known as Static
Member of classes.
3. Static member is also known as class member because its belong to the class.
4. Static keyword can only being prefix for member of the class.
2. Static Initialiser
3. Static Method
• Four Memory Area
When a java program is executing at the time of execution our JRE will request to
the RAM to provide some block of memory for execution.
A. Method Area
C. Stack Area
D. Heap Area
1. Method Area:
A block of memory will be created for a method of a class along with ‘Signature
and address’.
For every class a dedicated block of memory will be created inside static pool
with the name of class name. The block of memory which is allocated inside static pool
is also known class static area. All the static member of the class will get loaded inside
class static area along with its ‘Signature and address’.
3. Stack Area:
For Execution of every method the frame will be created inside stack area. The
frame will get created by following principle called ‘Last in First Out’ Stack area is
only used for execution purposes. Once the execution of the method or block is done
then the frame will be removed from the stack area.
4. Heap Area:
In Heap area a block of memory will be created for instance of a classes which is
also known Object. All the objects will be created with the help of reference. We can
access the member which is stored inside object by making use of ‘Reference and
Address’
A Method which is prefix with static modifier is known as Static Method. It is the
member of the classes.
1. For static method a block of memory will get created inside method area along with
reference and address and that reference will stored onside class static area. Hence we
can access static method using class name or using object reference.
2. Written in same class we can access the static method by using class name or by
using direct a method name but outside of the class. If you want to access to static
method we need to use class name.
Ex.
public class Demo
{
public static void test()
{
System.out.println(" from test() ");
}
public static void main(String[] args)
{
test();// Accessing Static method directly by using Method Name
test();// We can't Access test() outside from the class using method
// name
d.test();// we can access with the help of object reference also from
// outside of a class.
}
• Static Variable:
A variable which is declared inside the class block and prefix with static modifier
is known as static variable.
Characteristics of Static Variable
1. It is a member of classes.
2. Static variable are assigned with default value hence without initializing static
variable we can access them.
3. Static Variable are global in nature hence we can access static variable anywhere of
the class and outside of the class.
4. From a class we can access a static variable directly with it’s name using class name
and using object reference also.
5. The memory allocated for the static variable inside the class static area.
6. When a local variable and static variable names are same then always the 1st
preference will be given to local variable first. We can differentiate local variable
with the help of class name.
Ex.
public class A
{
static int k = 20;
Output
20
20
20
Ex.
public class B
{
public static void main(String[] args)
{
Output
From class B
20
20
• Static Initializers:
Syntax: static
// Instruction;
}
Characteristics of Static Initializer
1. Static initializer will get executed implicitly during loading process of a class.
2. A class can have any nu of static initializer which get executed from top to bottom.
2. The static initializer will executed before the execution of main method.
Ex.
public class StaticInIt
{
static int a;// Single Line Initializer
static int b = 20;
static // Multiline Initializer
{
System.out.println("From MLSI ");
}
public static void main(String[] args)
{
System.out.println("From Main() ");
System.out.println(a);
System.out.println(b);
System.out.println("End of the Main ");
}
}
Output
From MLSI
From Main()
0
20
End of the Main
Class Loading Process:
1. During execution a dedicated block of memory will get created for a class inside
static pool which can be access with the help of class name.
2. All the method definition and block of that particular class will get loaded inside
method area and the references of static member will get loaded inside class static
area or static pool.
3. Now static variable will get loaded inside class static area and assigns with default
values.
4. Then the static initializer will get executed from top to bottom. once the static
initializer execution is done then we can say the class loading process is completed.
5. Now the JRE will call main method for execution and the actual execution of a
program begins.
Ex.
public class StaticInIt1
{
static int k = 10;
static int l;
static
{
System.out.println(k);
k = 30;
l = 50;
}
static int c;
static
{
System.out.println(l);
}
public static void main(String[] args)
{
System.out.println(k);
System.out.println(l);
System.out.println(c);
}
static
{
System.out.println(l);
l = 20;
}
}
Ex.
• public class StaticInIt
{
static int a = test();
static int b = 20;
static
{
System.out.println(a);
System.out.println(b);
b = 40;
}
public static void main(String[] args)
{
System.out.println(a);
System.out.println(b);
test();
}
public static int test()
{
System.out.println(" From Test() ");
return 30;
}
}
• Static Context:
1. The block which is belong to the static method and multiline static initializer is called as
Static Context.
2. Inside a static context we can use or we can call static member directly.
3. Inside a static context we can not use non-static member directly, if we do so we get
compile time error.
4. This keyword is not allowed inside the static context.
Object Creation
1. Objects is an real-world entities.
2. According to the Oops concepts object is a memory which get created inside the Heap
Area.
3. Object has state (non-static variable) and behavior (non-static methods) associated with
them.
4. States also known as attributes and behavior also known as properties.
5. We can create any number of object for class.
6. Object are created during runtime of the program (Execution of the program).
• Step to create the class :
Step 1: Create a class or use existing class.
Step 2: Instantiation (The process of creating an object is known as Instantiation.)
Syntax: new ClassName( ) or Constructor( );
• Non- primitive Data type:
Non-primitive data type are used to creates non – primitive variables to stored reference of an
object. All the class name in java are non – primitive data type.
Ex.
public class EmployeeDriver
{
public static void main (String[] args)
{
Employee emp1 = new Employee(); // Instantiation.
System.out.println(emp1); // employee@15db9742
System.out.println(emp1.name); // null
System.out.println(emp1.eid); // 0
}
}
• Non – Static
1. Any number of a class which is non – prefix with static modifier is known as non – static.
2. Non – static member are belongs to instance of a class member or object member.
3. The memory allocation for non – static member is allotted inside object and object is
created inside the heap area.
Ex.
Any method which is declared inside a class block and not prefixed with static
modifier is known as non – static method.
1. A method block will get stored inside method area and if the method is non – static than
the reference of that method will get stored inside heap area.
2. We can not access non – static methods directly with its name or by using class name
inside static context.
Ex.
public class NonStaticMethod
{
public static void main(String[] args)
{
NonStaticMethod nsm = new NonStaticMethod();
nsm.test();
}
public void test()
{
System.out.println("From non - static Method of test() ");
}
}
3. Non – Static Initializer:
There are two type of non – static initializer
a. Single line Non – Static Initializer
Syntax: data type variableName = Data;
b. Multi-line Non – Static Initializer
Syntax:
{
// Statement;
}
• Non – Static Initializer will get executed during the object loading process.
• Non – Static initializer will get execute from top to bottom for every object creation.
• Non – Static initializer will get execute once for every object creation.
Ex.
public class NonStaticInitializer
{
int a = 10;
{
System.out.println("From MLNSI 1");
}
public static void main(String[] args)
{
System.out.println("from main()");
NonStaticInitializer nsi = new NonStaticInitializer();
System.out.println(nsi.a);
}
{
System.out.println("from MLNSI 2");
System.out.println(a);
a = 12;
}
}
Ex.
1. No Argument constructor
2. Parameterised constructor
1. No Argument Constructor:
A constructor which does not accept any formal argument is known as no argument
constructor. If programmer is fails to create a constructor then our compiler will add this no
argument constructor as a default constructor.
[Access Modifier] + [Modifier] + className ( )
{
// Statement;
}
2. Parameterised constructor:
The constructor which has formal argument is known as Parameterised constructor.
Syntax:
[Access Modifier] + [Modifier] + className [(Formal Argument)]
{
// Statement;
}
Purpose of Parameterised constructor:
1. Parameterised constructor is used to initialized the non – static variable by accepting the
data from the constructor from the object creation statement.
2. Parameterised constructor does not accepts no argument constructor.
Ex.
public class StudentDetails1
{
String name;
int id;
long cno;
String schname = "Parul University";
public void getAttribute()
{
System.out.println("Student Name: " + name);
System.out.println("Student Id: " + id);
System.out.println("Student Contact Number: " + cno);
System.out.println("School Name: " + schname);
}
public void initialize(String sname, int sid, long scno)
{
name = sname;
id = sid;
cno = scno;
}
public static void main(String[] args)
{
StudentDetails st1 = new StudentDetails();
st1.initialize("Laila", 420, 12345l);
st1.getAttribute();
StudentDetails st2 = new StudentDetails();
st2.initialize("Ram", 500, 98765l);
st2.getAttribute();
}
}
• Object Loading Process:
1. New keyword creates the block of memory inside the heap area called as object.
2. Then constructor will be called during the execution of program constructor loads all
non – static members of the class into the object created.
3. And executes all non – static initializer from top to bottom and the programmer written
instruction will get executed.
5. Object will get created successfully inside heap area and the reference is return.
6. The all above mentioned steps will happen once for every object creation.
Ex.
public class Program11
{
int c;
Program11(int e)
{
System.out.println("Programmer written instruction from Program11");
c = e;
}
{
System.out.println("From MLNSInIt");
}
int d = 34;
1. If class have more than one constructor with different formal argument is known as
constructor overloading.
Constructor Chaining:
2. This call statement should be the first statement inside the constructor.
3. We can not used multiple this called statement inside same constructor because to avoid
recursion.
4. If there are ‘n’ nu of constructor in our class then we used n – 1 this called statement.
public class StudentDetails
{
String name;
int id;
long cno;
static String schname = "Parul University";
StudentDetails(String name)
{
this.name = name;
System.out.println("From Student Details (String)");
}
StudentDetails(String name, int id)
{
this(name);
this.id = id;
System.out.println("From Student Details (String, int)");
}
StudentDetails(String name, int id, long cno)
{
this(name, id);
this.cno = cno;
System.out.println("From Student Details (String, int, long)");
}
public void getAttribute()
{
System.out.println("Student Name: " + name);
System.out.println("Student Id: " + id);
System.out.println("Student cno: " + cno);
System.out.println("School Name: " + schname);
}
public static void main(String[] args)
{
StudentDetails st1 = new StudentDetails("Laila", 420, 123456789l);
st1.getAttribute();
}
}
Que: Why Constructor name is same as class name?
Ans: Because every class object is created using the ‘ new ’ keyword , so it must have
information about the class to which it must created an object.
There are four pillar of Oops concepts
Data Hiding :- Data hiding it is the process of restricting the direct access to the data
member by providing indirect secured access via methods. With the help of data hiding we
can provide security for our data members by providing verification and validation.
for data hiding we can make a use of getter and setter method.
Getter method:- Getter method is used to get the data and fetch the data.
Setter Method:- Setter method is used to set the data and modify the data.
2. Inheritance:-
• Inheritance is the process acquiring properties from Parent class to Child class. It’s
comes under Is-a Relationship.
• Is-a relationship means parent and child relationship.
• All properties from Parent class will get inherited to child class expect private member,
constructor, multiline initializer.
• We can achieved inheritance between class to class with the help of extends keyword.
• We can achieved inheritance between class to interface with the help of implements
keyword.
Que: Why we used Inheritance in Java?
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Phrase used in Inheritance
1. Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
2. Sub Class or Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
3. Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
4. Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.
There are five type of Inheritance
1. Single level Inheritance:- Inheritance is possible only one level it Known as single
level inheritance.
2. Multi level Inheritance:- Inheritance is possible more than one level is known as
multi level inheritance.
3. Hierarchical Inheritance:- If the parent class is having more than one child at
same level is known as hierarchical inheritance.
4. Multiple inheritance:- If the child class is having more one parent at same level it
is known as multiple inheritance. Multiple inheritance is not possible in java.
5. Hybrid Inheritance:- Hybrid inheritance is possible with the combination of any
two type of inheritance is known as hybrid inheritance.
3. Polymorphism:
The object has the ability to undergoes in multiple forms or different forms is known
as Polymorphism.
If the association between method called statement and the method declaration statement
is achieved during compile time and same behaviour is executed is known as compile
time polymorphism and It is also known as Static Polymorphism.