Page 236 - Cs_withBlue_J_C11_Flipbook
P. 236
A constructor is a member function that has the same name as that of a class and is used to initialise the instance
variables of the objects that are created.
Syntax:
class [name_of_class]
{
//data members
// A constructor
[name_of_class]()
{
//Statements;
}
//methods
}
Let us see the following programs.
Program 6 Define a class named ParkingLot with the following description:
Instance variables/Data members
String vno : To store the vehicle number
int hours : To store the number of hours the vehicle is parked in the parking lot
double bill : To store the bill amount
Member Methods
ParkingLot() : Non-parameterised Constructor
void input( ) : To input and store the vno and hours
void calculate( ) : To compute the parking charge at the rate of `3 for the first hours or
part thereof, and `1.50 for each additional hour or part thereof.
void display ( ) : To display the detail
Write a main method to create an object of the class and call the above methods.
1 import java.util.*;
2 class ParkingLot {
3 String vno;
4 int hours;
5 double bill;
6 PartkingLot()
7 {
8 hours=0;
9 bill=0.0;
10 }
11 void input()
12 {
13 Scanner sc = new Scanner(System.in);
14 System.out.print("Enter vehicle number: ");
15 vno = sc.next();
16 System.out.print("Enter hours: ");
234234 Touchpad Computer Science-XI

