4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

CONSTRUCTORS

IMPORTANT TERMS AND DEFINITIONS


1. Constructor.

A constructor is that unit ofa class which is used to initialise the data members. The name of th
is same as the class name. A constructor automatically gets invoked whenever an object of the class is crea
2. General format of defining a constructor.
c1assName( )
{
statements;
}
3. Why is a constructor

an important part of java class?


A java class basically consists of:
(a) The declaration of member variables
(b) The constructor (or constructors)
(c) The methods
The declared member variables in a class may have private access which protects them from being used dire
the class, i.e., objectname.variableDeclaredPrivate=Value;
is an invalid statement if written in another clas .
values to such variables, constructors need to be defined.
4. Points to remember while defining constructor.
(a) Name of the constructor should be same as the name of the class.
(b) Do not write any returning data type keywords like void, int, double, char, etc. before the constructor
(c) A constructor should be defined with a public access specifier or no access specifier to give it the defa
(d) Do not call the constructor explicitly. It gets called itself (i.e., the statements in the constructor get executeiJf,c:.::t
object is created.
5. Default Constructor
or Non-Parameterized
Constructor.
A default constructor does not accept any p....,--values from the object when it gets created.
6. Example of Default Constructor
in MyClass.
class MyClass

{
private int c;
MyClass( )
{

/*Declaring member variable c*/


/*Defining a default constructor*/

c=IO;
}

7. Parameterized

Constructor.
object when it is created.
8. Example of parameterized
class MyClass2

These constructors
Constructor.

{
int c;
public MyClass2(int
{
c=num;
}

num)

}
9. Creating an object in the default
class CreateObject
{
public static void maine )

60

'7~

constructor.

Computer Applications (X)

have arguments.

The values to these arguments

are pas

{
MyClass ob=new MyClass();

1* Here MyClass is the name of another class as


defined in point 6 whose object is being created *1

static void maine )


int a=25;

IC

MyClass2 ob=new MyClass2(a);

II Here, MyClass2 is the name of another class and ob its new objects.

}
}
Formal parameters.
The arguments in the first line of definition of the constructor are called formal parameters. Within
'he constructor definition, the values of these formal parameters (or formal variables) are used to initialise the private
ata members.
Actual parameters.
The arguments passed to the constructor function from the object are called actual parameters. The
alues of actual parameters get copied to the formal parameters.
Example of formal parameters.
lass Numbers
int a, b;
Numbers (int x, int y)

{
a= x;
b = y;
}
the above example, x and yare formal parameters
Example of Actual parameter .
class AnotherClass

for the constructor.

public static void main ( )


{
intp=5,q=-I;
IICr"eating object of class Numbers
Numbers obj=new Numbers (p, q);
}
the above example, p and q are actual parameters which store actual values which are passed to formal parameters in
s Numbers defined in point 13.
onstructor Overloading.
Defining more than one constructor for a class where they differ in the parameter types or
.nnber of parameters passed to the constructor is called constructor overloading. In this case, the constructors get called
....tomatically with respect to the wayan object is created.
ample of Constructor
overloading.
s Example
private int a, b; private float c;
Example (int num I, int num2)
{
a=numI;

I*Constructor

I*1

I*Constructor2

*I

b=num2;
}
Example()
{

Constructors

a=O;
b=O;

}
public static void main()
{
J*calls constructor2*J

Example obj 1=new Example();


Examp\e ob)2=new Exam?le(S.9,20);
Example obj3=new Examp\e(S,6);

'* cans
J*calls
!*End
J*End

}
}
17. Destructor.
destructor's

A destructor is a member method that gets invoked when the object scope ends. Remember that concept
is limited to language C++. Java supports destruction of objects through its garbage collection feature.

SECTION-A

of the class is created?


constructor gets called when object is created.

2. Explain the concept of constructor

[2011)

overloading

an example.
Ans.

with
(2011)

Constructor
Overloading.
Defining more than one
constructor
for a class where they differ in the
parameter types or number of parameters passed to
the constructor is called constructor overloading. In
this case, the constructors
get called automatically

with respect to the wayan object is created.


3. State two features of a constructor.
(2010)
Ans. Features of constructor:
(i) The name of the constructor is same as the class
name.
(ii) A constructor automatically gets invoked whenever
an object of the class is created.

4.

(a) Differentiate
between
Actual Parameter.

Formal Parameter and

Or
Write the difference between formal parameters
actual parameters.
Give example to illustrate.
(b) Why do we need
member?

a constructor

and

as a class
(2007)

Ans. (a) Formal parameters


are the list of parameters
specified
in the function
prototype.
These
parameters accept the values passed to them (at the
time of function call) by corresponding
actual
parameters.

@3J 7~

~~

SHORT ANSWER TYPE QUESTIONS

1. Which unit of the class gets called, when the object


Ans.

constructor 3 *'
constructor I*J
of main*!
of class*!

Computer 'Applications (X)


\

Actual parameters
are the list of parameters
specified
in the statement
that calls th
function. These are the variables that actually sto
the value which is passed to the formal paramete _
and then used up in the function definition.
Separate memory locations are created for act
parameters and formal parameters. The valu _
stored in actual parameters get copied to form
parameters
and then used in the body of t _
constructor method.
For example:
void fun(float x, int y) {
J* x and yare formal
parameters
System.out.println(x);
int d= y+IO;
System.out.println( d);
}
void abet)
{ int a=5;float b=lS;
J* b and a are actual parameters whose
values ae passed in x & y respectively *
fun(b,a); }
(b) A constructor is used to initialize values to the
data members of the class.
For example: class Abc {
short x;
int y;
Abc() {
J* a non-parameterized constructor * J
x=I;

y=234;
}

Ans.

class Swap{
inta, b;
Swap(int x, int y){

it gets created.
Example of Default Constructor
in MyClass.
. class MyClass
{
private int c;
I*Declaring member variable c*1
MyClass( )
I*Defining a default constructor*1
{
c=IO;
}
}
Enter any two variables
through
constructor
parameters and write a program to swap and print
the values.
[20051

System.out.println("a="
+a);
System.out.printin("b
=" +b);}
public static void maine )
{
int u = 50, v = 100;
Swap ob = new Swap(u, v);
System.out.println("Original
Values :");
ob.display( );
System.out.println
("Swapped Values :");
ob.method'Swapf);
ob.displayt);
}
II end of main
II end of class

ICE nUESTUlNS

1. Which unit of a class gets called when the object of


the class is created?
A constructor gets called when the object of the class
gets created.
What is the use of a constructor
in a java class?
A constructor is generally used to assign the initial
values to private data members ofthe class. The private
data members are not accessible outside the class by
any means. And if there rises a need to initialise them
with values for an object, then they can be assigned in
a constructor.
This constructor
gets invoked
automatically when an object of the class is created in
the same or any other class.
What are the two types of constructors?
The two types of constructors are default constructor
and parameterized constructor.
Define a parameterized
constructor
for the class
Floppy that assigns the diameter and storage space
passed to it to the member variables 'diameter' and
'space'.
Floppy(double d, double s)
{
diameter=d;
space=s;
}
- Write the difference between default constructor
and parameterized
constructor.
default or a non-parameterized constructor does not
accept any values as parameters.

6.
Ans.

7.
Ans.

8.

Ans.

9.

Ans.

A parameterised constructor accepts arguments. The


initial values are supplied to the arguments at the time
of object creation.
Can the number of actual parameters be different
from the number of formal parameters ?
No, number of actual parameters should be same as
the number of formal parameters
defined in the
constructor, if the object is attempting to invoke-the
same constructor.
If a programmer
does not define a constructor in a
class, can he not create object in his program?
If a constructor is not defined, programmer can very well
create an object of the class because, the compiler itself
supplies a default constructor that initializes all instance
variables (member variables) to default values.
(a) How many constructors
can a class have?
(b) What
is the implicit
return
type of a
constructor?
(a) A class can have any number of constructors
defined for itself provided that they differ in their
arguments.
(b) Constructors do not have any return type not even
void because the implicit return type of a
constructor is the class type itself.
What is the difference if a constructor
is defined
with the private/protected
access from the ,one
defined with the public access?
If a constructor is defined with a public access, the
object of the class can invoke the constructor

Constructors

("
e ou
System.out.println("1t

The process 0 e mmg


for a class is called constructor overloading. The
number or data type of the arguments
that the
constructors take will vary.
11. Why do constructors
need to be overloaded?
Ans. Constructor overloading allows different initial values
for different
objects.
For example,
a default
constructor may initialise private, integer variables a
and b as O. Another constructor may accept int values
x and y to be assigned to a and b. Yet, another
constructor may accept two integer and one float value
to be assigned to a, b and a float variable c.
These constructors
get invoked depending on the
parameters
passed to constructors
during object
creation.
class Example {
int a, b;
float c;
Example() {a=O; b=Oj]
Example(int

x, int y)

Ans.

(a)

Errorl
Correction
Error2
Correction
Error3
Correction
Errorl
Correction

*1

Error2
Correction

x, int y, float z) I*Constructor3*1

Error3

{
a=x; b=y; c=z;

Correction

xU)

{
Example obj=new Example(5,
I*lnvoking

6, 2.5);

*1

Example st=new Example(30, lO);


I*lnvoking

Constructor2*1

}
12. Point

the errors

and

make

corrections

in the

following parts of java code:


(a) class CheckError
private char x;
private boolean b;
cbeckerrorC);
{

x=='A';
b==truej

7~

: checkerror();
: CheckError()
II name of constructor
: x=='A';
: x='A';
: b==true;
: b=true;

: public void CheckConst


(double d, boolean a)
: public CheckConst
(double d, boolean a)
: public void main(String x[])
: public static void main
(String x[])
CheckConst objt
=New CheckConst
(false, 5.29);
CheckConst objt
=new CheckConst
(5.29, false);

13. What is a destructor?


Ans. A destructor is a member method that gets invoked
when the object scope ends. The memory allocated
to objects by the constructor gets deallocated when a
destructor
gets invoked automatically.
In java.
concept
of destructor
is implemented
by it
garbage collection mechanism. We can not defin

Constructor3*1

Example objt=new Example();


I*lnvoking Constructorl

5.29);

}
}

I*Constructor2*1

}
public static void main(String

CheckConst
objt
=New CheckConst(false,

[a=x; b=y.}
Example(int

x]

(b)
I*Constructorl

public void main(String

is"+a);

wid Computer Applications (X)

a destructor
in our class.
What is a destructor's
name?
A destructor's name is same as that of a class name
What is the returning type of a destructor?
A destructor does not return any value so it has no
returning type not even void just as constructors.
16. Differentiate
a constructor
from a destructor.
Ans. A constructor gets invoked when an object is created
while a destructor gets invoked when the object is no
longer needed, i. e., the scope of the object comes to

14.
Ans.
15.
Ans.

an end.

A constructor allocates memory and is used to initialise


alues while a destructor's work is to deallocate this
memory to the free pool of memory locations.

class can have any number of constructors.


What is the garbage collection feature of java ?
In java, the new operator allocates the memory for the
objects during the run time of a program. The memory
occupied by these objects is deallocated when no
references to the objects exist. This memory can be
reclaimed. In java, this deallocation is performed
automatically and is called the garbage collection
eature.
Read the following code segments and answer the
questions that follow:
(a) private int Xj
/*Private member variable*/
public GetOutput(short a)
/*Constructor definition */
x=++a +--0 + ++aj
System.out.printlntx);
}
public void funcO
{
GetOutput ojt=new GetOutput(4)j
/*Assume main method
calls funcO*/
}
(I) Name the class in which above code may be

defined.
(it) What value will the variable a store when

the object is generated (created).


a store after the code gets
executed?
(iv) What will be the output if the above code is
executed assuming that method func is
called in the main method.
(b) private boolean var;
private int value;
public Sample (boolean m, int var)
{
var=m;
value = 2*var--+ --varj
}
public void funct )
{
int k=4j boolean b =false;
Sample s = new Sample(b, k)
(iil) What value will

(I) Name the class in which the above code

is defined.
Name the formal parameters in the code.

private int x, Yj
public total;
public Sum(int a, int b)
{

x=a;
y=b;

total = x+y;
}
public static void main
(String x] J)
{

Sum tot=new Sum(50, 46)j


System.out.print
("Total of 50 and 46 is" +tot.total);
}
}
(I) Write all data members of class Sum.
(it) Write all member methods of the class

Sum.
(iil) Can you access variables x and y in its

public static void main( )as follows:


System.out.print("Total
of"+ tot.x +
"and"+ tot.y +" ="+ tot.total);
Give reason for your answer.
(iv) Can you access x and y in another class
MyAccount's public static void main
as follows:
System.out.println("x
is"+x);
System.out.print("y is"+y);
Write the statement if there is any other
way to access it.
(v) In the above code, how many times will
Sum() get invoked.
(d) class Display
{
private short aj private int b;
public static void main(String x] J)
{
System.out.println
(20 +" *" + 30 + "=" + 20 *30)j
System.out.print
(20 + " * " + 31 + " = "+ 20 *31)j
}

Constructors

(j)

(i) j=O and i=O before any object is created.


(ii) class xyz
{

-Abcr ){
System.out.println("Object
}

Destroyed ");

_2. Write the characteristics

of a constructor.

of Constructor

(a) When an object is created, a constructor


is
invoked automatically by compiler to initialise
all member variables to zero. [This case rises
when a constructor
is not defined
by the
programmer in the class].
(b) Constructors are the member methods so they
obey usual access rules specified by public,
private and protected keywords.
(c) A constructor has the same name as that of its
class.
(d) It does not have any return type, not even void.
(e) A constructor body can contain any java statement
but its most common use is to assign values to
private data members.

Write the characteristics

of a destructor.

SECTION-B

of destructor:

(a) A destructor is invoked automaticall


compiler to destroy objects.

public static void mainO{


Abc obiectl=new Abc

c ass
c
static int j, i;
Abc(){ System.out.println
(" Abc object is now created ");
}
Abc(int a){
i=a;
j*=i;}

Characteristics

Ans. Characteristics

(b) Account( ){i=O; j=O;}

-Account(){ }
(c) Date dt=new Date(20,08,2000);
Date dt=new Dater);
Ans. (a) If a Time class contains the constructor defined
as Time(){
}, the constructor gets invoked on
creation of an object but does nothing while, the
second constructor when invoked would initial ise
data members a and b to value zero.
(b) The first statement is a constructor
of class
Account,
that initialises
instance variables
i and j to 0, while the second statement is a
destructor of class Account that automatically
deinitialises all instance variables of all objects.
(c) The first statement
creates an object dt by
invoking its parameterized constructor. The object
gets initialized with values 20,8 and 2000. While
the second statement creates an object and calls
the default constructor.

25. What will be the default initial values of (a) an


integer variable, (b) a float, (c) a boolean variable,
(d) an object, (e) a string variable?
Ans. (a) Default value of an integer variable=O
(b) Default value of a float variable=O.O
(c) Default value of a boolean variable=falsc
(d) Default value of an object variable=NULL
(e)

Default value of a string variable=NULL

LONG ANSWER TYPE QUESTIONS

US YEARS' aUESTI[]NS
Write a class with name employee and basic as its
data member, to find the gross pay of an employee
for the following allowances and deduction. Use
meaningful variables.
Dearness Allowance = 25% of Basic Pay
House Rent Allowance = 15% of Basic Pay
Provident Fund = 8.33% of Basic Pay
Net pay = Basic Pay + Dearness Allowance +
House Rent Allowance

the

_
Gross Pay = Net Pay - Provident Fund.
[20051

Ans. import java.io. *;


class employee
{

double basic;
II Data Member
II Constructor to initialise basic salary
employee (double b)

Constructors

!!!!!!!!!!!!!!

--

You might also like