Lecture#06 Constructor
Lecture#06 Constructor
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?
◾ 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).
//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
//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
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
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
◾ 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
◾ 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.