Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java - 5.1 Constructors PDF

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

JAVA

1 5.1 Java Constructors


CONSTRUCTORS
 It is a special function which has the same name as its
class and is syntactically similar to a method.

 A constructor initializes an object when it is created.


 It is automatically called when an object is created
 Constructors have no explicit return type
 Are typically declared public.
 Can not be inherited
// Example: A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass() {
x = 0; 2
}
}
TYPES OF CONSTRUCTORS

Default Parameterized Copy


Constructors Constructor Constructor

3
DEFINITIONS

4
DEFAULT CONSTRUCTOR
 Its of 2 type

User Provided by
Defined the system

 If no constructor is written, Java automatically


provides a default constructor that initializes
all member variables to zero.

5
PARAMETERIZED CONSTRUCTOR
 When a constructor takes in arguments it is known as
parameterized constructor
 The actual values are passed during object creation

// Example: A parameterized constructor.


class MyClass {
int x;

// Following is a parameterized constructor


MyClass( int n) {
x = n;
}
6
}
COPY CONSTRUCTOR
 A copy constructors initializes the instant variables of
an object by copying the initial value of the instance
variables from another objects. e.g.
class xyz
{ Actual x,i = 4 , z,j = 10
int a,b;
xyz(int x,int z)
{ a=x; b=y;
}
xyz(xyz& p) //copy constructor
{ a=p.x; b=p.y;
}
}
Test t1, t2;
t2 = t1; 7
OVERLOADING CONSTRUCTOR
 Like methods, constructors can also be overloaded. Since the
constructors in a class all have the same name as the class, their
signatures are differentiated by their parameter lists.
 A class can have any number of constructors
class student {
int roll; float marks;
student(int r, float m) // constructor with two argument.
{ roll=r; marks=m;
}
student(int r) // constructor with one argument
{ roll=r; marks=0;
}
student() // default constructor
{ roll=0; marks=0;
} 8
}
PROGRAM

9
THIS KEYWORD
 this keyword in Java is a special keyword which can be
used to represent current object or instance of any class in
Java.
 It stores the address of current calling object
 It is also known as reference or pointer to current object.
 Any instance method can be called as this.method() and
any instance variable var as this.var.

public class Actor


{
string lastName;
public Actor(String lastName)
{
this.lastName = lastName;
}} 10
TEMPORARY INSTANCES OF A CLASS

If we don't assign an object created by the new


operator to a variable then it is known as a
temporary instance or an anonymous object. If
we want to use an object only once, then we can
use it as a temporary instance.
class Sum {
int x; int y; int s;
public Sum() { x = 5; y = 10; }
public void computeSum() { s = x + y;}
public static void main(String[] args) {
new Sum().computeSum(); }
} 11
PROGRAMS
Define a class named fourSide, having
members as:
Data members:
length, breadth
Member Functions:
i. Overloaded constructor to initialise the
dimension of the four-sided figure with a square
and a rectangle.
ii. Compute the area and display it.
Also create the main() method to show the
implementation of the above methods. 12
PROGRAM
A class Palin has been defined to check whether a positive number is a
Palindrome number ornot. The number „N‟ is palindrome if the original
number and its reverse are same. Some of the members of the class are
given below:
Classname :Palin
Data members/instance variables:
• num : integer to store the number
• revnum : integer to store the reverse of the number
Methods/Member functions:
• Palin( ) : constructor to initialize data members with legal initial
values.
• void accept( ) : to accept the number.
• int reverse(int y) : reverses the parameterized argument „y‟ and stores
it in „revnum‟.
• void check( ) : checks whether the number is a Palindrome by invoking
the function reverse( ) and display the result with an appropriate
message.
Specify the class Palin giving the details of the constructor( ),
void accept( ),int reverse(int) andvoid check( ) 13
Define the main( ) function to create an object and call the
functions accordingly to enable the task.
PROGRAM
A class CheckEvil has been defined which checks if a number
has three 6 in it. For e.g. if number given is 661064 it is evil
no:
Classname :CheckEvil
Data members/instance variables:
 num : integer to store the number
 status : To store 0 for non-evil and 1 for evil.
Methods/Member functions:
• Constructor to initialize data members
• void accept( ) : To accept the number.
• int check() : To check if number is evil and update status
accordingly
• void print( ) : Prints the number and whether it is evil or
not.
Define the main( ) function to create an object and call 14
the functions accordingly to enable the task.
QUESTIONS
Q1 class _____ {
static int i, j;
Abc() { System.out.println(“Object Created”); }
Abc(int a) { i = a; j*=i; } }
1. What is the name of the class?
2. Which object oriented concept is used over here when 2 methods
have the same name?
3. Compute the value of i and j if the value passed to Abc(int a) is 5.
4. Write the statement to create object of this class when no value is
passed.
Q2 What is difference between constructor and a method?
Q3 Why we use copy constructor?
Q4 What is the purpose of this keyword in Java? 15
Q4 Create a class SalaryCalculation that is described as below:
Class Name : SalaryCalculation
Data members :
name (String type data)
basicPay, specialAlw, conveyanceAlw, gross, pf, netSalary AnnualSal (All
double type data)
Member methods :
i. SalaryCalculation( ) - A constructor to assign name of employee (name), basic
salary (basicPay) of your choice and conveyance allowance (conveyanceAlw) As `
1000.00
ii. void SalaryCal( ) - to calculate other allowances and salaries as given:
specialAlw = 25% of basic salary.
pf = 8% of basic salary
gross = basicPay + specialAlw + conveyanceAlw.
netSalary = gross - pf.
AnnualSal = 12 months netSalary.
iii. void display( ) - to print the name and other calculations with suitable
headings.
Write a program in Java to calculate all the details mentioned above
and print them all.
16
CONSTRUCTOR QUESTIONS
1. What is the difference between parameterized and copy constructor?
2. What happens if you do not specify a constructor?
3. Find and underline the errors in following code.
class My class {
int a,b;
void My class(int x, int y) {
x = a;
y = b;
}
int My class(int x) {
a=b=x;
}
void show( ) {
System.out.println(a+ “ “+y);
}
public static void main(String args[]) {
My class ob1=new My class();
My class ob2=new My class(12,14,15);
My class ob3=new My class(7.5); 17
ob1.ob2.ob3.show();
} }
4. Define a class PhoneBill with the following descriptions.
Data members:
customerName of type String
phoneNumber of type long
no_of_units of type int
rent of type int
amount of type float.
Member Functions:
i. calculate( ) This member function should calculate the value of amount as rent+
cost for the units. where cost for the units can be calculated according to the
following conditions.
No_of_units Cost
First 50 calls Free
Next 100 calls 0.80 @ unit
Next 200 calls 1.00 @ unit
Remaining calls 1.20 @ unit
ii. A constructor to assign initial values of customerName as “Raju”, phoneNumber
as 259461, no_of_units as 50, rent as 100, amount as 100.
iii. A function accept( ) which allows user to enter customerName, phoneNumber,
no_of_units and rent and should call function calculate( ).
iv. A function Display( ) to display the values of all the data members on the 18
screen.
FILL IN THE BLANKS
Question 1
A member function having the same name as that of the class name is
called ____.
Question 2
A constructor has ____ return type.
Question 3
A constructor is used when ______ is created
Question 4
A constructor without any argument is known as ___________
Question 5
____________ constructor creates objects by passing value to it.
Question 6
The ______ keyword refers to the current object.
Question 7
The argument of a copy constructor is always passed by __________.
Question 8 19
The constructor generated by the compiler is known as ___________.
TRUE/FALSE
 Question 1
 The compiler supplies a special constructor in a class that does
not have any constructor.
Question 2
 A constructor is not defined with any return type.
Question 3
 Every class must have all types of constructors.
Question 4
 A constructor is a member function of a class.
Question 5
 Constructor is used to initialize the data members of a class.
Question 6
 A constructor may have different name than the class name.
Question 7
 A constructor is likely to be defined after the class declaration.
Question 8
 Copy constructor copies functions from one object to another. 20
Define a class Bill that calculates the telephone bill of a consumer with the
following description:
Data Members Purpose
int bno bill number
String name name of consumer
int call no. of calls consumed in a month
double amt bill amount to be paid by the person

Methods Purpose
Bill() constructor to initialize data members with default initial value
Bill(...) parameterised constructor to accept billno, name and no. of calls consumed
Calculate() to calculate the monthly telephone bill for a consumer as per the table
Display() to display the details
Units consumed Rate
First 100 calls ₹0.60 / call
Next 100 calls ₹0.80 / call
Next 100 calls ₹1.20 / call
Above 300 calls ₹1.50 / call
21
Fixed monthly rental applicable to all consumers: ₹125
Create an object in the main() method and invoke the above functions to
perform the desired task.
FILL IN THE BLANKS
Question 1
A member function having the same name as that of the class name is
called constructor.
Question 2
A constructor has return no type.
Question 3
A constructor is used when an object is created
Question 4
A constructor without any argument is known as non-parameterised
constructor.
Question 5
Parameterised constructor creates objects by passing value to it.
Question 6
The this keyword refers to the current object.
Question 7
The argument of a copy constructor is always passed by reference.
Question 8
The constructor generated by the compiler is known as default constructor. 22
TRUE/FALSE
 Question 1
 The compiler supplies a special constructor in a class that does not have any constructor.
True
 Question 2
 A constructor is not defined with any return type.
True
 Question 3
 Every class must have all types of constructors.
False
 Question 4
 A constructor is a member function of a class.
True
 Question 5
 Constructor is used to initialize the data members of a class.
True
 Question 6
 A constructor may have different name than the class name.
False
 Question 7
 A constructor is likely to be defined after the class declaration.
False
 Question 8
 Copy constructor copies functions from one object to another.
False
23
24

You might also like