Introduction to OOPS : Problems in procedure oriented approach, Features of Object Oriented
Programming System, Object creation, Initializing the instance variable, Constructors.
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
Java unit 7
1. Introduction to Java Programming Language
UNIT 7
[Introduction to OOPS : Problems in procedure oriented approach, Features of Object Oriented Programming
System, Object creation, Initializing the instance variable, Constructors.]
Procedure Oriented Programming (POP) decomposes the problems into small parts and then solve
each part using one or more functions.
Problems in procedure oriented approach
• Importance is not given to data but to functions as well as sequence of actions to be done i.e.
algorithm.
• Data moves openly around the system from function to function. It includes Global data,
created for sharing some required information across the system. This free or open access
can result in corruption of data accidentally.
• Adding new data or functionality to change the work flow require going back and modifying
all other parts of the program. In a large program it is very difficult to find or identify what
data is being used by which function.
• procedural code have a tendency to be difficult to understand, as it evolves, it becomes even
harder to understand, and thus, harder to modify.
• It is often difficult to design because it does not model the real world problem very well.
• It is difficult to create new data types. The ability to create the new data type of its own is
called extensibility. Procedure oriented programming is not extensible.
Features of Object Oriented Programming System
To overcome the limitation of Procedural oriented programming languages Object oriented
programmin languages were developed. Following are the features of OOPS:
Provided By Shipra Swati, PSCET, Bhagwanpur
2. Introduction to Java Programming Language
1. Emphasis on data rather than procedure.
2. Programs are divided into small parts called object.
3. Data structures are designed such that they characterized the objects [Class].
4. Data and related functions are enclosed in classes itself [Encapsulation].
5. Data is secured as they can’t be accessed by external functions [Data Hiding].
6. Objects may communicate with each other through functions [Message Passing].
7. Follows bottom-up approach in program design.
8. Using inheritance, a class can acquire properties of another pre-defined class [Inheritance].
9. Data Type can be created based on the necessity.
10. An operation may exhibite different behaviours in different instances. The behaviour
depends upon the types of data used in the operation [Polymorphism].
Object Creation
When we create class then we are creating new data type. Newly created data type is used to
create an Object of that Class Type. For example following is an example 'Rectangle.java', which
defines a new data type (class) 'Rectangle' and object of this class 'myrect1' is created.
class Rectangle{
int length;
int breadth;
public static void main(String a[]){
Rectangle myrect1; // Declaration
myrect1 = new Rectangle(); // Allocation and assigning
myrect1.length = 32;
myrect1.breadth = 15;
System.out.println(" Rectangle length is
"+myrect1.length+" and n Rectangle breadth is "+myrect1.breadth);
}
}
Creating object is two step process:
Step 1 : Declaration of Variable of Type Class
Rectangle myrect1;
▪ Above Declaration will just declare a variable of class type.
▪ Declared Variable is able to store the reference to an object of Rectangle Type.
▪ As we have not created any object of class Rectangle and we haven’t assigned
any reference to myrect1, it will be initialized with null.
Provided By Shipra Swati, PSCET, Bhagwanpur
3. Introduction to Java Programming Language
Step 2 : Allocation and Assigning Object to variable of class Type
myrect1 = new Rectangle();
▪ Above Statement will create physical copy of an object.
▪ This Physical Copy is then assigned to an variable of Type Class i.e myrect1.
▪ Note : myrect1 holds an instance of an object not actual object. Actual Object is
created elsewhere and instance is assigned to myrect1.
To summarize:
• First statement will just create variable myrect1 which will store address of actual object.
• First Statement will not allocate any physical memory for an object thus any attempt
accessing variable at this stage will cause compile time error.
• Second Statement will create actual object ranndomly at any memory address where it
found sufficient memory.
• Actual memory address of Object is stored inside myrect1.
Provided By Shipra Swati, PSCET, Bhagwanpur
4. Introduction to Java Programming Language
Instead of two seperate statements:
Rectangle myrect1 ;
myrect1 = new Rectangle();
single statement given below can also be used:
Rectangle myrect1 = new Rectangle();
Initializing the instance variable
Variables which are defined without 'static' keyword and outside any method in class is called
instance variable. Instance variables are object specific i.e. each object will have their own copy of
instance variables. Instance variables are also called class properties, fields or data member. Each
instance variable lives in memory for the life of the object it is owned by. Instance variables are
different from local variables, which are defined inside a method and has limited scope. Following
are some of the key differences between instance variable and local variable:
Difference Instance Variable Local Variable
Scope Instance variables can be been seen by all
methods in the class.
Local variables are visible only in the
method or block they are declared.
Declaration Instance variables are declared inside a
class but outside a method.
Local variables are declared inside a
method or a block.
Life Time Instance variables are created using new
and destroyed by the garbage collector
when there are no reference to them.
Local variables are created when a
method is called and destroyed when
the method exits.
Acceess
Modifiers
instance variables can have access
modifiers ( private, public, protected etc.)
local variables will not have any
access modifiers.
Access instance variables can be accessed outside
the class, if they are declared as public.
Local variables can't be accessed from
outside the methods or blocks they are
declared in.
Storage Instance variables are stored in heap. Local variables are stored in stack.
Initialization If no value is assigned to Instance
variables, they will have default values
based on their type. Following is the list of
default values for different types:
Instance Variable Type Default Value
boolean false
byte (byte)0
short (short)0
int 0
long 0L
char u0000
float 0.0f
double 0.0d
Object null
Local variables must be assigned some
value by the code, otherwise the
compiler generates an error.
Provided By Shipra Swati, PSCET, Bhagwanpur
5. Introduction to Java Programming Language
Accessing Instance Variable:
• Using dot operator - If the instance variable is declared as public, it can be accessed using
dot operator (ex- myrect1.length is the above given code).
• Using public member method of the class – If the instance variable is not public, then it
will not be visible outside the class, but it can be accessed by any method, which is defined
in the class itself (member method). So, if there is any method, which is declared as public
can be used to access the instance variable.
For example Rectangle.java (code listed in above section) can be re-written as
Rectangle1.java, when the fields 'length' and 'breadth' of the class Rectangle is defined as
private and not public.
class Rectangle1{
private int length;
private int breadth;
void rectDesc(){
length = 32;
breadth = 15;
System.out.println(" Rectangle length is "+length+"
and n Rectangle breadth is "+breadth);
}
public static void main(String a[]){
Rectangle1 myrect1; // Declaration
myrect1 = new Rectangle1(); // Allocation and assigning
myrect1.rectDesc();
}
}
Here, rectDesc() is a public member method, which is able to access the instance variable, even if
they are private. This method can be accessed from outside the class Rectangle1 using its object
myrect1.
Initializing instance variable:
For initializing an instance variable, it needs to be accessible in someways. And now, we know that
any instance variable can be accessed in following ways:
1. Direct initialization: The instance variable can be assigned a value directly, when they are
declared in a class.
Class <className>{
<type> <instanceVariableName> = <value>
}
Provided By Shipra Swati, PSCET, Bhagwanpur
6. Introduction to Java Programming Language
2. Using dot operator: If instance variable is public, it can be assigned a value using dot
operator having generalized syntax as:
<objectName>.<instanceVariable> = <Value>
3. Using a public member method: If the instance variable is declared as private, it can be
assigned a value using any public instance method, which can accept arguments compatible
with instance variables and assign these values to instance variables. For example:
Class <className>{
private <type> <instanceVariableName_1> ;
private <type> <instanceVariableName_2> ;
public <returnType> methodName( <type> <arg1>, <type> <arg2>, )
<instanceVariableName_1> = <arg1>;
<instanceVariableName_2> = <arg2>;
}
These public methods can be called using instance of the class as shown in example
Rectangle1.java.
As every Objects contain there own copy of Instance Variables. It is very difficult to
design a code that initializes each and every instance variable of each and every object of
Class using an instance method. Java allows objects to initialize themselves when they are
created. Automatic initialization is performed through the use of a constructor, which is
explained in next section.
Constructors
Constructor in java is a special type of method that is used to initialize the object. Like methods, a
constructor also contains collection of statements (i.e. instructions) that are executed at time of
Object creation. Java constructor is invoked at the time of object creation. An object is created using
keyword new like below:
MyClass obj = new MyClass();
Every class has a constructor. If we don't explicitly declare a constructor for any java class, the
compiler builds a default constructor for that class. However when we implement any constructor,
then we don’t receive the default constructor by compiler into our code. Follwoing diagram
demonstrates the idea:
Provided By Shipra Swati, PSCET, Bhagwanpur
Constructor of MyClass is called
7. Introduction to Java Programming Language
Some important points about Constructor :
1. Constructor name is same as that of “Class Name“.
2. Constructor don’t have any return Type (even Void). But a constructor returns current
class instance.
3. Constructor Initializes an Object.
4. Constructor cannot be called like methods but Constructors are called automatically as
soon as object gets created.
5. Constructor can accept parameter and can be overloaded.
Types of Constructors:
There are two types of constructors:
1. Default constructor or,
(no-arg constructor)
2. Parameterized constructor
• Default Constructor: A constructor that have no parameter is known as default constructor.
Syntax of default constructor: <class_name>(){..............}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
at the time of object creation.
class Bike1{
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Default constructor provides the default values to the object like 0, null etc. depending on
the type, if no explicit value is assigned.
Provided By Shipra Swati, PSCET, Bhagwanpur
8. Introduction to Java Programming Language
• Parameterized Constructor: A constructor that have parameters is known as parameterized
constructor. Parameterized constructor is used to provide different values to the distinct
objects.
public class Employee {
int empId;
String empName;
//parameterized constructor with two parameters
Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}
public static void main(String args[]){
Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}
• Following is a code that uses two constructors, a default constructor and a parameterized
constructor. When we do not pass any parameter while creating the object using new
keyword then default constructor is invoked, however when we pass a parameter then
parameterized constructor that matches with the passed parameters list gets invoked.
class Example2 {
private int var;
//default constructor
public Example2(){
this.var = 10;
}
//parameterized constructor
public Example2(int num){
this.var = num;
}
public int getValue() {
return var;
}
public static void main(String args[]){
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}
Provided By Shipra Swati, PSCET, Bhagwanpur
9. Introduction to Java Programming Language
The program give above has more than one constructor that take different number of
arguments. So, we can say that constructor is overloaded here. Constructor overloading is
a technique in Java in which a class can have any number of constructors that differ in
parameter lists. The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type. So, each constructor can be used performs
different set of task.
A constructor can also accept argument of type class i.e. an object and can copy all the
values of existing object into newly created object. This type of constructor may be termed
as Copy Constructor. Following is an example of copy constructor:
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Other than initialization, another type of operation can also be performed in constructor.
Provided By Shipra Swati, PSCET, Bhagwanpur