KEMBAR78
Soda Chapter 7 | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
143 views20 pages

Soda Chapter 7

A constructor is a special member function that is automatically called when an object is created. It initializes the object's member variables. Constructors can be default (no parameters) or parameterized (with parameters). Default constructors initialize member variables to default values, while parameterized constructors allow passing initial values as arguments.

Uploaded by

dinesh9866119219
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views20 pages

Soda Chapter 7

A constructor is a special member function that is automatically called when an object is created. It initializes the object's member variables. Constructors can be default (no parameters) or parameterized (with parameters). Default constructors initialize member variables to default values, while parameterized constructors allow passing initial values as arguments.

Uploaded by

dinesh9866119219
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 7

What is a constructor?
A constructor is a special member function which is automatically called when an instance of the class
is declared the task of the constractor is to initialize the definition of the variable with the initial
assignment.

It is called constructor because contains the values of data members of the class.

Example:

Class car{

String name;

String model;

Car () //constructor (with the sae name of the class)

Name =” “;

Model =” “;

Characteristics of constructors

1. Constructors are the special member functions and have as the class itself has.
2. Constructors have no return value specification.
3. Constructors is called when an object of the class is created
4. Constructors are used to initialize the data members of the class
5. A constructors cannot be inherited
6. Public constructors ar available for all methods
7. Private and protected constructors are accessible only by member methods.
Distinction between constructor and method

Constructor Method
A constructor has the same name as the class A method can have any name
has
It has no return type It has return type
Constructor is called automatically A method has to be invoked
It initializes data members It can do various functions
Need for a constructor
Constructors have one purpose in life: to create an instance of a class. This can also be called
creating an object, as in:
Mobile p1=new mobile();
The purpose of methods, by contrast, is much more general. A method’s basic function is to
execute java code.
Declaration of constructor
A constructor can not be called directly. When an instance of class is created, java allocates
memory for the object and initializes that object instance variable either or to default value.
Look at the roll owing example:
Class staff{
Private string name;
Private string address;
Private double salary;
Private double day;
Private double hra;
Private double gross;
//class constructor
Staff(){
Name =” “;
Address=” “;
Salary=0.0;
}
}

In the given example, a default constructor staff() has been declared with the same name of the class.
It assign default values into data members.

Null

Null is a keyword in java. It refers to a null object and it can be used for any object reference. It is not
equivalent to zero.

Types of constructors

Basically there are two main types of constructors in java.

 Constructors which can receive parameters (alle parameterized constructor)


 Constructors which cannot receive any parameters (called non-parameterized constructor).
No-parameterized constructors are called default constructors.

in other words, we can say that java provides the following two constructors

1. Default constructor (with no parameters)


2. Parameterized constructor (with parameters)
A third type of constructor is also there. This is called copy constructors. But this type of
constructor is derived from the parameterized constructor and only creates a copy of the existing
constructor object. Copy constructors define the actions performed by the complier when copying
class objects. A copy constructor has one formal parameter that is the type of the class (the
parameter may be a reference to an object). It is used to create copy of an existing object of the
same class.

Let us first study the main two types of the constructors.

1. Default Constructors
A default constructor is a special member function which initializes the data members of a
class. It is called default constructor because it declares no parameters. A default constructor
accepts no arguments.
Illustration-1
Class measuring {
Private double kilometer;
Private double meter;
Private double centimeter;
Private double millimeter;
Measuring () {
Kilometer=10.0;
Meter=120;
Centimeter=12.0;
Milometer=5.0;
}
Void output data() {
System.out.printin (“length=’+kilometer+”kilometer”+metre+”metre”);
System.out.print (+centimeter+”centimeter”+millimeter+”millimeter”);
}
}

In the above illustration, default constructor i.e. measuring () initializes values to the private data
member; 10.0 to kilometer,120 to meter, 12.0 to centimeter and 5.0 to millimeter.

The output data () member function is plays the output of the class.
Illustration-2

Import java.*;

Class employed {

Private string empname;

Private string address;

Private string city;

Public double salary;

Private double gross pay;

Private double da, hra,pf, netpay;

Employed () {

Empname =”RITIKE MALHOTRA”;

ADDRESS=”6406,JALVAYU VIHAR”;

CITY=”PANCHKULA-HARYNA”;

Salary=4670;

Public void output data () {

System out-print in (“============================”);

System .out.printin (“name of employee:” +empname);

Syatem.out.printin (“address:::” +address);

System.out.printin (“city:::”+city);

System.out.printin (“basic pay :::”+salary);

Public void calculated(employed x){

da = 0.35* salary ;

System. Out. Print in (“DA =” +da);


}

Public void calculator (employed x){

hra = 0.1 *salary ;

System .out. Print (“HRA= “ + hra) ;

Public void pfdeduction (Employed x ) {

Pf = 0.12 * salary ;

System. out.println (“PF Decurion =” +pf );

Public void calculate gross (employed x){

Gross pay=salary+hra+da;

Syatem.out.printin (“gross salary of employee=”+grosspay);

Public void caculatenetpay (employed x){

Net pay =grosspay-pf:

System.out.printin(“net pay of employee=”+net pay);

}
Note; save this above program with the second class name i.e., construct example.

In this illustration, the default constructor automatically passes the values into private members.
The class constructor employed Is default constructor which initializes the values into data
members.

2. Parameterized Constructors
The constructors which can take different parameters are referred to as Parameterized
Constructors. The parameterized constructors pass initial values as arguments into the
constructor object.
Java does not compel the user to write a constructor for the class. If no constructors are written,
Java provides a default constructor, which will have the following properties :
1. The default constructor provided by Java will be a no-argument constructor.
2. The default constructor will call the no-argument constructor of the super class.
3. Java will not provide the default constructor If you have written at least one constructor in the
class.
Let us take an example :
Measure (double, double, double, double);
It means that Measure constructor has four parameters in its body. There are values which will be
passed to parameterized constructor.
It is possible for a Java constructor to take parameters. These parameters can then be used to
initialize the internal state (fields) of the newly created object.

As you can see, three parameters are declared: first, last and year. Inside the body of the
constructor the values of these three parameters are assigned to the
Fields of the Employee object.
The line breaks after each parameter are optional. The Java compiler ignores line breaks
here. You can also write the parameter declaration in a single line if you
Want, like this:
Public Employee (String first, String last, int year) {
First Name = first;
last Name = last;
Birth Year = year;
}
To call this constructor that takes three parameters, you would instantiate an employee
object like this:
Employee employee = new Employee("Neha", "Vikrant", 2000);
The parameters are passed to the constructor inside the parentheses after the class name on
the right side of the equal sign. The object is then created, and theconstructor executed.
After execution of the above constructor, the fields initialized by the constructor will have the
values of the parameters passed to the constructor.
Rectangle (int fen, int bre) {
length = len;
breadth = bre;
>
>
Class Rectangle Demo {
Public static void main(String args[]) { Rectangle rl = new Rectangle(20 10);
f

System.out.println (" Length of Rectangle : " + rl.length);


System.out.printlnC'Breadth of Rectangle : " + rl.breadth);

//Initialization of values by parameterized class constructor Measure(double a, double b, double c, double d) {


kilometre = a; metre = b;
centimetre = c;
millimetre = d;
}
void outputdata() {
System.out.print(+(+kilometre * 1000 + metre + centimeter / 100 + millimetre 1 1000));
System.out.print(" metres");
}
}
class Measurement {
public static void ma/n() {
//Constructor calls automatically
V4 * '

new Measurefioo ,c
Measure distance *
-5, 35.5);
5ystem.out.pr/nt('Tota/ Length = °' d/stance.outputdata()-
}
Output of the Program
Total Length = 10015.2105 metres
PASSING INITIAL VALUES AS AR6UMFMK
in the previous topic of
Measure(10.0,15.0,17.5, 35.5); and double d respectively. ' ' The parameterized
UUUUIC L

constructors can pass value as :


(j) an implicit call
(ii) through an explicit call
Passing Initial Values as an Implicit Call
An implicit call constructor retrieves the parameterized constructor even if it is not
declared in the main(). To extract the values in the parameterized constructor, you can
create an object with initial values as follows :
MeasuringflO.0,120,12.0, 5.0);
Now the constructor would be called implicitly.
The above constructor passes four values 10.0,120,12.0 and 5.0 to double a, double b,
double c and double d.
c(ffusfra/iofi
//Use of implicit call constructor method, class emp {
private String empname;
private String address;
private String city;
private long salary;
import java.io.*;
double grosspay;
double da, hra, pf, netpay;
//class constructor
void inputdata(String a, String b, String c, long value) {

empname = a;
address = b;
city = c;
salary = value; }
public void outputdataO {
System.out.printlnC'=============-==z======:==
System.out.println ("Name of Employee +empname);
Sy stem.out.println ("Address +address);
System.out.println("Basic Pay +salary);
}
public void calculated(emp x) {
da = 1.5* salary;
—• .—>
System.out.println ("DA =" +da);
Java
>
public void calculatehra(emp x) {
hra = 0.1 * salary;
System.out.println ("HRA =" +hra);
>
public void pfdeduction(emp x) {
pf = 0.12 * salary;
System.out.println ("PF Deduction =" +pf);
}
public void calculate gross(emp x) { gross pay = salary + hra + da;
System.out.printlnf'Gross Salary of Employee =" +gross pay);
}
public void calculatenetpay(emp x) {
netpay = grosspay - pf;
System.out.println("Net Pay of Employee =" +netpay);
>
>
class Implicit Constructor {
public static void main(String args[]) throws lOException {
emp employee = new empQ; employee.inputdata("Ram Shankar”, 1435/1",
"Lucknoww,8000);
employee.outputdataQ;
//Now Passing the reference of employee object.
employee.calculateda (employee);
employee.calculatehra (employee);
employee.calculatenetpay (employee);
utput of the Program

Passing Values through an Explicit Call


When entire object of a parameterized constructor is initialized at main( ) method, then it is
an implicit call constructor. The constructor is called itself to initialize the object whereas the
initial value of the private data
members can retrieve the constructor explicitly.
The explicit call to a constructor helps in creating a temporary instance or temporary object.
A temporary object remains in the memory as long as it is being used or referenced in an
expression.
3. Copy Constructor
While studying the types of constructors, we have mentioned another special type of
constructor i.e. Copy Constructor. Sometimes a programmer wants to create an exact but
separate copy of an existing object so
that subsequent changes to the copy should not alter the original or vice versa. This is made
possible using
the copy constructor.
A copy constructor is used to create a temporary object of a class object.
A copy constructor can do the following things :
(i) It can initialize and declare one object by another object of the same class. The process of
initialization through a copy constructor is called copy initialization.
(ii) It can return objects as a function value. Use of Copy Constructor
A copy constructor is a constructor that creates a new object using existing
object of the same class and initializes each instance variable of tif|Q object with
corresponding instance variables of the existing object Z
argument. This constructor takes a single argument whose type is that of ^ containing
the constructor. e
Copy constructors are widely used for creating duplicates of objects kno* cloned objects.
Duplicate object will have the same characteristics of the ortH 8s
object from which duplicate object is created. But we have to ensure that^' original and
duplicate objects refer to different memory locations.

Total Length = 10015.2105 metres


1 ^py of the Measure Object =

10015.2105 metres
Let! Vs. Know More
^lustration-j
Copy constructors are widely used for duplicate
objects known as cloned objects. Duplicate object
has the same charac- teristics of original object,
but both the objects refer to different memory
locations.
class Rectangle { int length;
int breadth;
}
//constructor to initialize length and breadth of rectangle Rectangle(int len, int bre) {
length = len; breadth = bre;
//copy constructor Rectangle (Rectangle obj) {
System.out.println ("Copy Constructor Invoked"); length = obj.length;
Breadth= obj.breadth;
}
//method to calcuate area of rectangle int area() {
return (length * breadth);
}
}
//class to create Rectangle object and calculate area class CopyConstructorExample {
public static void main(String args [ ]) { Rectangle firstRect = new Rectangle(4, 5);
Rectangle secondRect= new Rectangle(firstRect); System.out.printlnfArea of First
Rectangle :"+ firstRect.area());
System .out.println("Area of Second Rectangle :"+ secondRect.area());
}
}
In the above program, the statement,
Rectangle firstRect = new Rectangle(4, 5);
creates a Rectangle object and invokes the constructor Rectangle (int len,int bre) which
initializes values length and breadth with values 4 and 5 respectively and
Returns the reference to firstRect variable. The statement,
Rectangle secondRect = new Rectangle (firstRect); invokes a copy constructor
Rectangle (Rectangle obj) Rectangle object and return*.
and initializes the instance variables length and breadth of the newly ere returns lts

reference to the secondRect variable.


CONSTRUCTOR OVERLOADING
Constructors can also be overloaded like methods. With different initial values of data,
we can generafe objects of a class by overloading constructors.
Constructors can be overloaded provided they should have different arguments because
Java Virtual Machine
differentiates constructors on the basis of arguments passed in the consrru .
Whenever we assign the name of the method same as that of class name, this method
should not have any return type. This is called constructor overloading.
In the following example, three overloaded constructors have been used and each of
them has different arguments types :
JjllusiraUon
class Overloading { int x;
float y; //Constructor no. 1
OverloadingO { x = 0;
y = 0;
} //Constructor no. 2
Over!oading(int a) {
x = a; y = 0;
}
//Constructor no. 3 Overloading (int a, float b) {
x = a;
y = b;
}
Public static void main(String args[]) {
Overloading objl Overloading obj2
Overloading obj3
New Overloading; new Overloading (15);
New Overloading (10, 5.5F);
//constructor no.l //constructor no.2
//constructor no.3
}
>

7

••

Calling a Constructor inside another Constructor r^tna another constructor in the same class
from constructor is called constructor chilling. By using this () we can call another
constructor in the same class . in case we want to call another constructor, this() should be
the first line in the constructor below example shows code for constructor chaining.

Class my chaining {
My chaining (){
System.outprintJn ("In default constructor

>
My Chaining (int i) {this();
System.outprintln ("In single parameter constructor...'}
-
-

}
My Chaining (int i, int j) {

this (j);

System.out.println ("In double parameter constructor..."); }


Public static void main (String args[]) {
My Chaining ch = new My Chaining (10,20);
}
}
Output of the Program
In default constructor...
In single parameter constructor...
In double parameter constructor...
Constructing Class Objects
Objects of a class can be global or local to a function. When an object is created, the default
constructor of that object automatically calls it. It may also call another
constructor, which we specify in the declaration of object either implicitly or explicitly. When
the object is destroyed, destructor of that object is called if its
class declares any.
Global Class Objects
The constructor of a global class is called before the main function begins to run. All global
class objects are initialized before the program starts.
Let us take the example from one of our previous illustrations.
All global class objects are initialized before the
Program starts.
Measure distance = new Measure ();
The above declaration creates a global object distance of a class Measure. Before calling
main, Measure's class default constructor for distance is called which assigns
The value of measurements to the object.
To initialize the values of measurements, a global Measure class declares the object as follows :
Measure distance = new Measure (10.0. 15.0, 17.5, 35.5);
In such a case, Java searches Measure for a constructor, which can accept the ^J^^jibing arg UIT1

Here Java class measure's overloaded constructor initializes distance to the total of 10.0, 15.0, 17.5,
35.5. " When any constructor method finishes, global object's destructor is called.
S

Local Class Objects


The automatic class objects declared locally are created when the function is called and destroyed with
the end of the function.
void outputdata(void) {
Measure dist;
}
In the above segment, when the default constructor Measure is called to initialize the class object dist
for measurements, each time a statement calls the function. With the end of function, Java calls
measures
Destructor for the dist object. In such a way, it allows the object to clean up itself.
When we exit a program, global class object destructors are called normally but the destructors for any
other existing automatic variables that are local to a function, are not called.
Super ()
The method super () calls the parent's constructor which has the appropriate supplied parameters.
Whenever a subclass needs to refer to its immediate super class(base class), it can do so by using
super() method.
The method super () has two forms. In first form, it can call super class constructor. The second is
used to
Access a member of the super class, which has been hidden, by a member of a subclass.
Let us study the first form in which super() can call super class constructors.
Calling Superclass Constructors
A super class constructor can be called using the following syntax- super(parameter-list);
super( ) is executed inside a subclass constructor. It should be noted that superf ) should be the first
statement to be executed inside a subclass constructor.
[Uusfrafion
import java.io.*; / j class School {
private String name;
private String father,
Schoo!(String a, String b) {
name = a;
father = b;
}
public void output data() {
System.out.println ( "Name of the Student = " +nameV
System.out.println ( "Father's Name = • +father)-
>
}
//First derived class
Class Student extends School {
Int roilno;
Double average;
Student (String a, String b, int c, double v) { super(a, b);
Roil no = c;
Average = v;
}
Void showdataQ {
System.out.printlnfRoll Number = " +roll no);
System.out.println ("Average Marks = • +average);
}
}
class Super class {
public void main() {
Student s = new Student ("Pratiek", "Sh.T.Malhotra", 123, 88.66); s.showdata();
s.outputdata ();
}
}
Output of the Program
Roll Number = 123
Average Marks = 88.66
Name of the Student = Pratiek.
Father's Name = Sh.T.Malhotra
In the above program segment, the Student ( ) calls super( ) with the parameters a,b,c
and v. The constructor Student () is called for initializing name and father using these
values. The Student ( )
Does not initialize these values itself. This allows the base class to make the values of
name and father.
Therefore, it is obvious from the above program that super () is called with an object of
type Student and not of type School.
The class School has the knowledge of its own members.

* 4.*

classFruit Juice {
private int product code;
private String flavor;
private String pac_type;
Private int pack size;
Private int product price;
Void Frui£Juice () { //Constructor

Product code=0; flavor = " ";


Pacjype =
Pack size = 0; product price = 0;
HM

}
Void fnputflnt pc, String f, String pt, int ps, int pp) { product code=pc;
Flavor = f;
Pacjype = pt; pack size = ps;
Product price = pp;
System.out.printlnC'Product Code = +product_code);
n

System.out.println ("Flavor =" +flavor);


System.out.println ("Pack Type =" +pac_type);
System.out.println ("Pack Size =" +pack size);
System.out.printlnC'Product Price =" +product price);

void discount() {
product _price = product price - 10;
System.out.println("Discounted Price =" +product price); }
void display() {
System.out.println ("Product Code = " +product code);
System.out.printlnf'Flavour =" +flavor);
System.out.println ( PackType =" +pac_type);
u

System.out.println ( Pack Size = " +pack size);


M

System.out.println("Product Price = " +product price);


}
}
2. Define a class taximeter having the following description:

Create an object in the main method and call all the above methods in it.
Answer, class taximeter {
int taxino;
String name;
int km;
float bill;
taximeter() //Constructor
{ taxino = 0
name = /
3. Define a class Student described as below: Data members/instance variables:
Name, age, ml, m2, m3 (marks in 3 subiPrt^
_ Jects) maximum, average
1 J bUD /

Member Methods:
(i) A parameterized constructor to initialize the data members (ii) To accept the details of a
student
(iii) To compute the average and the maximum out of three marks
(iv) To display the name, age, marks in three subjects, maximum and average.
Write a main method to create an object of a class and call the above member methods.
Answer. Import java.util. Scanner;
Public class Student {
String name;
Int age;
Int ml, m2, m3;
Int maximum;
Double average;
Public Student () {
}
Public Student (String n, int a, int marks, int marks2, int marks3, int max, double avg) {
Name = n;
Age = a;
Ml = marks;
m2 = marks2;
m3 = marks3;
Maximum = max;
Average = avg;
}
public void accept Details() {
Scanner scanner = new
Scanner(System. in);
System.out.printf'Enter name:");
name = scanner.next();
System.out.printf'Enter age:");
age = scanner.nextlntQ;
System.out.print ("Enter marksl :");
ml = scanner.nextlnt();
System.out.printC'Enter marks2:"');
m2 = scanner.nextlnt ();
System.out.printC'Enter marks3 :");
m3 = scanner.nextlnt ();

public void compute() {


average = (ml + m2 + m3) / 3.0;
maximum = Math.max(ml, (Math.max(m2, m3)));
}
public void display() {
System.out.println ("Name: " + name);
System.out.printlnfAge: " + age);
System.out.println ( Marksl: " + ml);
M

System.out.println ("Marks2: " + m2);


System.out.println ( Marks3: " + m3);
n
System.out.println("Maximum: " + maximum);
System.outprintlnfAverage: " + average);
}
public static void main(String args[ J) { Student student = new Student();
student.acceptDetails(); student.compute();
student.display();
}
}
4. Define a class movieMagic with the following description:
Instance variables/data members:int year : to store the year of release of a movie
String title : to store the title of the movie
float rating : to store the popularity rating of the movie
(minimum rating = 0.0 and maximum rating = 5.0)
Member methods:
(i) movie Magic()
Default constructor to initialize numeric data members to 0 and String data member to "".
(ii) void accept() : To input and store year title and rating.
(iii) void disp\ay(): To display the title of a movie and a message based on the rating asper the table.
Rating Message to be displayed
0.0 to 2.0 : Flop
2.1 to 3.4 :Semi-hit Hit
3.5 to 4.5 : Hit
4.6 to 5.0 ;Super
Write a main() method to create an obiect of the class and call the above member methods.
Answer. import java.io.*;
class movie Magic {
Print int year;
Private String title;
Private float rating;
MovieMagicQ { //constructor
Year = 0;
Title =
ii n

Rating = O.Of;
}
void accept() throws I Exception {
Buffered Reader reader = new Buffered Reader(new InputStreamReader (System. in));
System.out.println ("Enter the year::");
String y = reader.readLineQ;
Year = Integer.parselnt(y);
System.out,println("Enter the title::");
Title = reader.readLineQ;
System.out.println ("Enter the rating ::");
String r = reader.readLine ();
Rating = Float.parseFloat(r);
}
Void display() {
if (rating < 0) {
System.out.println ("Wrong Input");
System. exit(0);
}
if(rating >= 0 && rating <= 2.0) {
System.out.println ("Flop");
}
if(rating >= 2.1 && rating <= 3.4) {
System.out.println ("Semi-hit"); }
J if(rating >= 3.5 && rating <= 4.5) {
System.out.println ("Hit");
}
if(rating >= 4.6 && rating <= 5.0) {
System.out.printlnfSuper Hit");
if (rating > 5.0){
System.out.println("Wrong Input(range is 0 - 5)");
System. exit(O);
}
 A constructor is a special member function that is automatically called when an instance of a
class is declared
 A constructor is called when an object of the class is created
 Constructor can be used to initialize the data member of a class
 A default constructor is a special member function that initialize the objects
 Constructors may be overloaded so single class may have more than one constructor, all
which have the same but constructor is to initialize the instance variable of an object when
the object is instantiated
 You can think of the default constructor as a constructor which does not taken any
parameters
 Use super to call a constructor in a print class
 Calling the constructor for the super class must be the forst statement in the body ofa= a
constructor

You might also like