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

Lecture#06 Constructor

The document provides an overview of constructors in object-oriented programming, detailing their purpose, types, and usage in Java. It explains default, no-argument, and parameterized constructors, along with the significance of the 'this' keyword for resolving variable name collisions. Additionally, it includes examples and practice questions related to constructors and class design.

Uploaded by

qmumer7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture#06 Constructor

The document provides an overview of constructors in object-oriented programming, detailing their purpose, types, and usage in Java. It explains default, no-argument, and parameterized constructors, along with the significance of the 'this' keyword for resolving variable name collisions. Additionally, it includes examples and practice questions related to constructors and class design.

Uploaded by

qmumer7
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

OBJECT ORIENTED

PROGRAMMING
C O N S TRU C TO R & IT S
TYPES
OUTLINE

◾ What is
constructor?
◾ Types of
constructors
◾ Examples
◾ “this” Keyword
CONSTRUCTOR
◾ A constructor is a special member function of a class that is executed
whenever we create new objects of that class.
◾ Constructor is automatically called when the object is created.
Constructors are not usually called explicitly by us.
◾ Constructor is used to initialize the objects of a class.
◾ Every time an object is created using the new() keyword, at least one
constructor is called.
◾ Constructor Properties
◾ Constructor is a special function having same name as the class name
◾ Constructor does not have return type, not even void.
◾ This is because the implicit return type of a class constructor is the class type itself.
CONSTRUCTOR
Are constructors always public?

No, Constructors can be public , private , protected

or default. Can constructor be private?

Yes, we can declare a constructor as private. If we declare a


constructor as private we are not able to create an object of a
class.
5
TYPES OF CONSTRUCTORS
There are three types of
constructors

◾ Default constructor
◾ No-argument constructor
◾ Parametrized constructor

6
DEFAULT CONSTRUCTOR

◾ When we don’t define a constructor for a class, Java compiler will create
a default constructor for you having a null body (one that does nothing).

◾ A default constructor is a constructor that takes no arguments and


performs no processing other than the reservation of memory.
◾ The default constructor automatically initializes all instance variables to zero.

◾ It will always be called by the compiler if no user defined constructor is


provided.
◾ Once we define our own constructor, the default constructor is no longer
used.
DEFAULT CONSTRUCTOR

//Java Program to create and call a default //Java Program to create and call a default
constructor constructor
class Bike class Bike
{ {
/ main method //creating a default
public static void main(String args[]) constructor Bike()
{ {}
//calling a default //main method
constructor Bike public static void
b=new Bike(); main(String args[])
} {
} //calling a default 8

Test.java constructor
Bike b=new Bike();
NO-ARGUMENT CONSTRUCTOR

Constructor with no arguments is known as no-arg


constructor.
The signature is same as default constructor, however
body can have any code.

Unlike the default constructor where the body of the


constructor is empty.
9
SYNTA X TO DEFINE N O ARGUMENT C O NSTRUCTOR

public class MyClass


{

//This is the
constructor
MyClass()
{ }
..
}
NO-ARGUMENT CONSTRUCTOR
Although you may see some people claim that that default and no-arg constructor is
same but in fact they are not, even if you write public Demo() { } in your class
Demo it cannot be called default constructor since you have written the code of it.
class D emo
class D emo
{ {
public D emo() public D emo()
{} {
public static void main(String args[]) System.out.println("This is a no argument
{ constructor");
Demo d=new Demo(); }
} public static void main(String 11

} args[]) { Demo d=new


}
Demo();
}
CONSTRUCTO
RS
/* Here, Box uses a
constructor to initialize the width =
dimensions of a box. 10;
*/ height =
class Box 10;
{ double }
depth =
width; / compute
10; and return
double volume double
height; volume() {
double
return width * height *
depth; depth;
}
/ This is the
}
CONSTRUCTORS
class BoxDemo6 {
public static void main(String args[]) {
/ declare, allocate, and initialize Box
objects
Box mybox1 = new
Box(); Box mybox2
= new Box(); double
vol;
/ get volume of first
box vol =
mybox1.volume();
System.out.println("V Constructing
olume is " + vol); Box
/ get volume of Constructing
Box Volume
second box
PARAMETRIZED CONSTRUCTOR

◾ The methodof passing parameter to a


constructor is same as passing parameter to normal
function.

◾ The only difference is that the parameters are passed to the


constructor when the object is declared.

◾ It is possible to pass one or more arguments to a constructor


function.
PARAMETRIZED CONSTRUCTOR
public class
Employee
Class Main {
{
public static void main(String args[])
int empId; {
String Employee obj1 = new
empName;
//parameterized constructor with two Employee(10245,“xyz"); Employee obj2
parameters Employee(int id, String = new Employee(92232,“abc");
name) obj1.info();
{ obj2.info();
empId = id; }
empName = name; }
}
void info()
{ 15

System.out.println("Id: "+empId+"
Name: "+empName);
PARAMETRIZED
CONSTRUCTOR
class
Example
{ private int var;
public Example(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example myobj = new Example(6);
System.out.println("value of var is: 16

"+myobj.getValue());
}}
EXAMPLE OF NON-PARAMETERIZED A N D PARAMETERIZED
class Example
{
private int
var; public //non-parameterized
Example() constructor
{
var =
public Example(int
10; //parameterized public static void main(String args[])
{
num) } constructor
Example obj = new
{ Example(); Example obj2 =
var = num; new Example(100);
} System.out.println("var is:
public int "+obj.getValue());
getValue() System.out.println("var is: 17
{ "+obj2.getValue());
var is:
return var; }
10
What if there are multiple constructors

// Constructor with default arguments


Rectangle() {
length = 0;
width = 0;
Public static Void main(string[] arg)
}
{
// Constructor with one arguments
// Invokes the default constructor
Rectangle r=new Rectangle();
Rectangle(double len) {
length = len;
// Invokes the constructor with one argument
width = 0;
Rectangle r1(10.0);
}
// Constructor with 2 arguments
// Invokes the constructor with two arguments
Rectangle r2(10.0, 2.0);
Rectangle(double len, double wid) {
length = len;
}
width = wid;
}
Complete program in notes below.
PARAMETERIZED CONSTRUCTORS

Box(double w, double h,
/* Here, Box uses a
parameterized constructor double d) { width = w;
to initialize the dimensions height =
of a box. h;
*/ depth =
class Box { d;
double width; }
/ compute
double and return
height; volume
double double
Program volume()
continues on
{ next
PARAMETERIZED CONSTRUCTORS
class BoxDemo7 {
public static void main(String args[]) {
/ declare, allocate, and initialize Box
objects Box mybox1 = new
Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
/ get volume of first
box vol =
mybox1.volume();
System.out.println("V
olume is " + vol);
}/ get volume of
Volume is
} second box 3000.0
vol =
THE THIS KEYWORD

◾ this can be used inside any method to refer to the current


object.

◾ That is, this is always a reference to the object on which


the method was invoked.
THE THIS KEYWORD

/ A redundant use of this.

Box(double w, double h, double d) {


this.width = w;
this.height = h;
this.depth =
d;
}
THE THIS KEYWORD

◾ It is illegal in Java to declare two local variables with the same name
inside the same or enclosing/nested scopes.
◾ However, we can have local variables including formal parameters to
methods, which overlap with the names of the class’ instance variables.
◾ When a local variable has the same name as an instance variable, the
local variable hides the instance variable.
◾ This is why width, height, and depth were not used as the names of the
parameters to the Box() constructor inside the box class.
◾ this lets us refer directly to the object, we can use it to resolve any
name space collisions that might occur between instance variables and
local variables.
THE THIS KEYWORD

/ Use this to resolve name-space


collisions. Box(double width, double
height, double depth)
{
this.width =
width;
this.height =
height;
this.depth =
GARBAGE COLLECTION

◾ How the objects are destroyed and their memory released for later
reallocation?
◾ Java handles de-allocation automatically.
◾ The technique that accomplishes this is called garbage collection.
◾ It works like this:
◾ When no references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed.
EXAMPLE: A STACK CLASS
else
// This class defines an integer stack that can hold
10 values. stck[++tos] = item;
class Stack { }
int stck[] = new int[10]; / Pop an item from the stack
int pop() {
int tos;
if(tos <
// Initialize top-of-stack
0) {
Stack() {
System.out.println("Stack
tos = -1;
underflow."); return 0;
}
}
// Push an item onto the stack
else
return stck[tos--];
void push(int item) {
}
if(tos==9)
} continues on next
Program
System.out.println("Stack is
EXAMPLE: A STACK CLASS
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++)
mystack1.push(i);
for(int i=10; i<20; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
} }
PRACTICE Q U E S T I O N
◾ Define a class H OTEL in java with the following
description:
◾ Private Members
//Data Member to store Room No
◾ · RNo
//Data Member to store customer
◾ · N ame N ame
◾ · Tariff //Data Member to store per day
◾ · NOD
charge
//Data Member to store Number of
◾ Public Members:
days
◾ · A parameterized constructor function to initialize data
members
3
◾ · CALC( ) //A function to calculate and return amount as 0

NOD*Tariff
TASK 2
◾ Create a class for a bank account that includes the following data members
◾ N ame of depositor
◾ Account Number
◾ Type of account
◾ Balance amount in the account
• The class also contains the following member functions
◾ A constructor to assign initial values
◾ Deposit function to deposit some amount. It should accept amount as parameter.
◾ Withdraw function to withdraw an amount after checking the balance. It should accept
amount as
parameter.
◾ Display function to display name and balance
Passing Array to Constructor
Create an Encapsulated class Student with following characteristics:
Data Members:
String Name
Int [] Result_array[5] // Result array contains the marks for 5 subjects

Member functions:
Student ( String name, int arr[]) // Constructor
Average () // it calculates and returns the average based on the marks in
the array.

Now create a class Runner:


Create two objects of type Student and set values (Name and Array) via constructor.
Then call the Average method for both objects and return the calculated average to the main
function. Then compare the Average of both Students and display which student has higher
average.
Class Student
Class Runner having main function

You might also like