Constructors - Questions & Answers
EXERCISE
Part A : Objective Type Questions
1. A constructor is automatically called (invoked) when the object is created.
(a) destroyed (b) created (c) called (d) none of these
2. A constructor will have both a & b.
(a) name of class (b) no return type (c) both a & b (d) none of these
3. A constructor is used for initialising the data members of an object when it is created with legal initial values.
(a) initialising (b) destroying (c) simplifying (d) none of these
4. A default constructor takes zero parameters.
(a) many (b) two (c) one (d) zero
5. When more than a single constructor exists within a single class it is known as constructor overloading.
(a) constructor overloading (b) function overloading (c) constructor overhauling (d) constructor overbearing
6. this keyword is used within a constructor to refer to the current object.
(a) public (b) class (c) this (d) new
7. A constructor that takes (b) or (c) parameters is called parameterised constructor.
(a) zero (b) one (c) more (d) (b) or (c)
8. A constructor declared as private can not be accessed outside the class.
(a) public (b) private (c) protected (d) static
9. In constructor definition, the parameters list refers to formal arguments.
(a) actual (b) formal (c) real (d) none of these
10. A constructor generated by compiler itself is called default constructor.
(a) parameterised (b) default (c) copy constructor (d) all of these
11. Mostly, a constructor is declared as public.
(a) public (b) private (c) protected (d) none of these
12. A simple constructor is created using new operator.
(a) new operator (b) class (c) public (d) none of these
Part B : Solved Questions
1. State the main features of a constructor.
The main characteristics of a Constructor are:
- A constructor will have the same name as that of the class and does not have a return type.
- A constructor cannot be static or final.
- A constructor must be declared public (if it has to be accessed outside the class).
- It is automatically called (invoked) when the object is created.
2. What is the need of a constructor as a class member?
Constructors are used to initialise the values of the instance variables. Whenever an object of the class is created, its constructor is called first (default constructor) by the JVM. The constructor sets the initial values of the instance variables.
3. What is a default constructor? Give its prototype with an example.
A constructor that takes no parameters is called a default constructor. It is also called non-parameterised constructor.
Its prototype is : <class_name> () { //body }
Example :
class Abc {
Abc() { } // Default constructor
}
4. How can you invoke a constructor?
A constructor is implicitly invoked when the object is created.
5. What is the significance of this keyword?
The this keyword is used to refer to the current object within a constructor. It actually refers to the object that has invoked the constructor. It stores the address of currently calling object.
6. How two constructors can be chained together?
Constructors can be chained together by invoking one constructor from another using this keyword. But this calling statement must be the first statement within a constructor. During execution, control just moves from one constructor to other till the data members are initialised and objects are constructed.
7. How an object is used as a reference variable?
The process of assigning one object to another object is called assigning object as a reference variable. Here assignment operator is used to assign reference variable.
e.g., Book b2 = b1;
Here b1 is an object with values and b2 is another object getting the reference of b1 object through assignment. Both are referring to the same (member) memory location. Thus, any change made to the value by one object will affect other as both are referring to same object.
8. Give the output of the following program.
public class Icecream {
private String brand;
private String flavour;
private float price;
public Icecream() {
this(20.5f);
System.out.println(" in default constructor...");
}
public Icecream(float x) {
brand = "Amul";
flavour = "Vanila";
price = x;
this.displayDetails();
}
public void displayDetails() {
System.out.println(" Brand : "+ brand);
System.out.println(" Flavour : "+ flavour);
System.out.println(" Price : "+ price);
}
public static void main(String args[]) {
Icecream ice1 = new Icecream();
}
}
Output of the program is:Brand : Amul
Flavour : Vanila
Price : 20.5
in default constructor...
9. (i) Label the following class with types of constructor.
class Abc {
int x;
int y;
Abc() { x = 0; y = 0; }
Abc(int a, int b) { x = a; y = b; }
}
(ii) Write the main() method with statements that will invoke both the constructors.(i)
Abc() // default constructor
Abc(int a, int b) // parameterised constructor
(ii)
public static void main(String args[]) {
Abc one = new Abc(); // default constructor invoked
Abc two = new Abc(10, 20); // parameterised constructor invoked
}
10. Find the error in the code given below.
public Product() {
System.out.println(" in default constructor...");
this(10, 20.5f); // invokes parameterised constructor1
}
The above code will result in a compiler error message saying, 'The call to this must be the first statement in a constructor'. It clearly means that, if you are using a this keyword to call constructors, it must be the first statement in the constructor. The control will move ahead and execute the rest of the statements as it returns back.
ASSIGNMENT
Part A : Very Short Questions
1. Can a constructor be declared static or final?
No, a constructor cannot be declared static or final.
2. Define a constructor.
A constructor is a special member method of a class without a return type. It is used for initialising and constructing the data members of an object when it is created.
3. Name the types of constructors in Java.
1. Default constructor (Non-parameterised constructor)
2. Parameterised constructor.
4. How many parameters can a default constructor take?
A default constructor takes zero parameters.
5. Which keyword must be used to call a constructor from within a constructor?
The 'this' keyword must be used to call a constructor from within another constructor.
6. What is the need for a constructor?
A constructor is used to implicitly initialise and construct the data members of an object with legal values exactly at the time it is created, especially since data members are often declared private for data hiding.
7. How does a constructor help in data hiding?
Data members are generally kept private to implement data hiding and abstraction, meaning they cannot be accessed or initialised directly outside the class. Constructors provide a safe, controlled way to implicitly initialise these hidden private members right when the object is created.
8. Write two main features which help you to identify a constructor in a class.
1. It always has the exact same name as the class it belongs to.
2. It does not have any return type, not even void.
9. What is temporary instance? How is it created?
A temporary instance is a process of using a memory location for an object without assigning it any name (reference variable). It is created using the new operator and constructor, and is used immediately, e.g.,
new Room1(12,11,11).display();
10. Can one object be assigned to another? Justify.
Yes, one object can be assigned to another using the assignment operator (e.g., Book b2 = b1;). When this is done, the second object gets the memory reference of the first object. Both refer to the same memory location, so any change made by one object will reflect in the other.
11. Justify how constructors and member methods are similar?
Constructors and member methods are similar because both act as members of a class to perform functions, both can take parameters, both require an access specifier (like public), and both support overloading.
12. What is the purpose of new operator?
The new operator dynamically allocates memory for an object at run time and returns a reference to that memory location.
13. Which unit of the class gets called when an object is created? Give an example.
The constructor gets called automatically when an object is created.
Example: Book b1 = new Book(); // Invokes the default constructor of Book class.
14. Write a Java statement to create an object mp4 of class digital.
digital mp4 = new digital();
15. Write two characteristics of a constructor.
1. A constructor will have the same name as that of the class.
2. It does not have a return type, not even void.
Part B : Short Questions
1. State the difference between a constructor and a method.
Name: A constructor must have the exact same name as its class, whereas a method can have any valid name based on user's choice.
Return Type: A constructor has no return type (not even void), whereas a method must have a valid return type (or void).
Execution: A constructor is executed automatically only once at the time of object creation, while a method can be called repeatedly whenever required.
2. What is the difference between an object and an object's reference variable?
An object is the actual entity residing in dynamically allocated memory that holds data and methods. An object's reference variable is simply a pointer/variable that stores the memory address of that object.
3. How a temporary instance of a class is different from object of a class?
A regular object has a reference variable (a name) pointing to its memory location, allowing it to be accessed multiple times throughout the program. A temporary instance does not have a name (reference variable) and its values are kept in memory only for as long as the single statement is executing, after which it is removed.
4. What do you mean by constructor overloading?
When more than a single constructor exists within a single class, each having a different parameter signature (number, type, or order of parameters), it is called constructor overloading.
5. How a constructor is declared?
A constructor is declared using an access specifier (usually public) followed by the class name, a set of parentheses for parameters (if any), and curly braces for its body, without any return type.
Syntax: <access specifier> class_name(parameter list) { //body }
6. Explain the significance of using 'this' keyword within a constructor definition.
The 'this' keyword refers to the current calling object. Within a constructor, it is highly significant because it helps to avoid naming confusions when instance variables and formal parameters share the exact same name. It is also used to chain multiple constructors together.
7. Can one constructor call another (default/parameterised constructor)?
Yes, one constructor can call another constructor within the same class using the 'this()' keyword. This is known as constructor chaining.
8. Write a Java class MyClass. The description of the class is as follows.
| Members | Member Name | Description |
|---|---|---|
| Instance variable | age | To store age of a student. |
| Constructor | MyClass() | Initialises age to 14. |
| Main method | main() | Increment the age by 1. Display result. |
public class MyClass {
int age;
public MyClass() {
age = 14;
}
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.age = obj.age + 1;
System.out.println("Age: " + obj.age);
}
}
9. Write a Java class Box whose default constructor initialises the dimensions length, width and height of the box to zero. The parameterised constructor is passed three double values, each for its dimensions. Write a main method for the above class that creates a Box object of dimensions 3.89 cm, 2.1 cm and 1.5 cm. Compute the volume of this box.
public class Box {
double length, width, height;
public Box() {
length = 0.0;
width = 0.0;
height = 0.0;
}
public Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public static void main(String args[]) {
Box b1 = new Box(3.89, 2.1, 1.5);
double volume = b1.length * b1.width * b1.height;
System.out.println("Volume of the box is: " + volume);
}
}
10. Data members :
dd - date - integer
mm - month - integer
yy - year - integer
Member functions:
(i) default constructor.
(ii) parameterised constructor — initialise you and your friend's date of birth.
(iii) plus (int) — increase years of both date of birth with parameter value of both persons.
(iv) disp () — display actual and changed date of birth of both persons.
public class DateClass {
int dd, mm, yy;
public DateClass() {
dd = 1; mm = 1; yy = 2000;
}
public DateClass(int d, int m, int y) {
dd = d; mm = m; yy = y;
}
public void plus(int years) {
yy = yy + years;
}
public void disp() {
System.out.println(dd + "/" + mm + "/" + yy);
}
public static void main(String args[]) {
DateClass myDOB = new DateClass(10, 5, 2008);
DateClass friendDOB = new DateClass(20, 8, 2008);
System.out.print("Actual My DOB: "); myDOB.disp();
System.out.print("Actual Friend DOB: "); friendDOB.disp();
myDOB.plus(5);
friendDOB.plus(5);
System.out.print("Changed My DOB: "); myDOB.disp();
System.out.print("Changed Friend DOB: "); friendDOB.disp();
}
}
11. (i) Define a class 'Vehicle' having instance variables as numOfPassengers, fuelCapacity, fuelConsumed per litre.
(ii) Define a parameterised constructor to initialise their default values.
(iii) Create two objects TwoWheeler and FourWheeler of this class and display their details.
public class Vehicle {
int numOfPassengers;
double fuelCapacity;
double fuelConsumedPerLitre;
public Vehicle(int passengers, double capacity, double consumed) {
numOfPassengers = passengers;
fuelCapacity = capacity;
fuelConsumedPerLitre = consumed;
}
public void display() {
System.out.println("Passengers: " + numOfPassengers + ", Capacity: " + fuelCapacity + ", Consumed/Litre: " + fuelConsumedPerLitre);
}
public static void main(String args[]) {
Vehicle TwoWheeler = new Vehicle(2, 12.5, 45.0);
Vehicle FourWheeler = new Vehicle(5, 45.0, 15.5);
System.out.println("Two Wheeler Details:");
TwoWheeler.display();
System.out.println("Four Wheeler Details:");
FourWheeler.display();
}
}
12. Define a class named FruitJuice with the following description.
Instance variables/data members :
int product_code : stores the product code number
String flavour : stores the flavour of juice (e.g., orange, apple)
String pack_type : stores the type of packaging (e.g., tetra pack, PET bottle etc)
int pack_size : stores package size (e.g., 200 ml, 400 ml)
int product_price : stores the price of the product.
Member methods :
1. FruitJuice() : Default constructor to initialise integer data members to 0 and string data members.
2. void input() : To input and store the product code, flavour, pack type, pack size and product price.
3. void discount() : To reduce the product price by 10.
4. void display () : To display product code, flavour pack type, pack size and product price.
public class FruitJuice {
int product_code;
String flavour;
String pack_type;
int pack_size;
int product_price;
public FruitJuice() {
product_code = 0;
flavour = "";
pack_type = "";
pack_size = 0;
product_price = 0;
}
public void input(int code, String flav, String packT, int packS, int price) {
product_code = code;
flavour = flav;
pack_type = packT;
pack_size = packS;
product_price = price;
}
public void discount() {
product_price = product_price - 10;
}
public void display() {
System.out.println("Code: " + product_code);
System.out.println("Flavour: " + flavour);
System.out.println("Pack Type: " + pack_type);
System.out.println("Pack Size: " + pack_size);
System.out.println("Price: " + product_price);
}
}
13. Shasha Travels Pvt. Ltd gives the following discount to its customers.
| Ticket amount | Discount |
|---|---|
| Above Rs 70,000 | 18% |
| Rs 55001 to Rs 70,000 | 16% |
| Rs 35001 to Rs 55000 | 12% |
| Rs 25001 to Rs 35000 | 10% |
| less than Rs 25,001 | 2% |
Write a program to input the name and ticket amount for the customer and calculate the discount amount and net amount to be paid. Display the output in the following format for each customer.
Sr No. Name Ticket charges Discount Net amount
(Assume there are 4 customers).
import java.util.Scanner;
public class ShashaTravels {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Sr No.\tName\tTicket charges\tDiscount\tNet amount");
for(int i = 1; i <= 4; i++) {
System.out.print("Enter name: ");
String name = sc.next();
System.out.print("Enter ticket amount: ");
double ticketAmt = sc.nextDouble();
double discount = 0.0;
if(ticketAmt > 70000) discount = ticketAmt * 0.18;
else if(ticketAmt >= 55001) discount = ticketAmt * 0.16;
else if(ticketAmt >= 35001) discount = ticketAmt * 0.12;
else if(ticketAmt >= 25001) discount = ticketAmt * 0.10;
else discount = ticketAmt * 0.02;
double netAmt = ticketAmt - discount;
System.out.println(i + "\t" + name + "\t" + ticketAmt + "\t\t" + discount + "\t\t" + netAmt);
}
}
}
14. (i) Write a class called Rectangle with two float data members. Write a default and a parameterised constructor for the class to initialise the data members. Write the main() function to invoke both of them.
(ii) Write a method called showData() that will display the data of both the objects from the main method.
(iii) Write a statement to call the parameterised constructor from the default constructor using the this keyword. Also call the method from the parameterised constructor.
public class Rectangle {
float length;
float breadth;
public Rectangle() {
this(5.0f, 4.0f); // calling parameterised constructor
}
public Rectangle(float l, float b) {
length = l;
breadth = b;
this.showData(); // calling method
}
public void showData() {
System.out.println("Length: " + length + " Breadth: " + breadth);
}
public static void main(String args[]) {
System.out.println("Default constructor object:");
Rectangle r1 = new Rectangle();
System.out.println("Parameterised constructor object:");
Rectangle r2 = new Rectangle(10.5f, 2.5f);
}
}
15. (i) Define a class 'Find' to find out even/odd number. With the help of disp(), find whether an entered number is even/odd.
(ii) Create another class to initialise and use parameterised constructor through main() method.
class Find {
int num;
public Find(int n) {
num = n;
}
public void disp() {
if (num % 2 == 0) {
System.out.println(num + " is an Even number.");
} else {
System.out.println(num + " is an Odd number.");
}
}
}
public class TestFind {
public static void main(String args[]) {
Find obj = new Find(25); // initialising using parameterised constructor
obj.disp();
}
}
16. (i) Create a class with the following specifications :
Class Name : Calculate
Member variables : num
Constructor : Parameterised
Member method:
(a) reverse() to generate the reverse of a number.
(b) palindrome() to check whether an entered number is palindrome or not.
(c) prime() to check whether an entered number is prime or not
(ii) Add another class Demo having main() method with parameterised constructor to create object of class. Calculate and call the member methods.
class Calculate {
int num;
public Calculate(int n) {
num = n;
}
public void reverse() {
int n = num, rev = 0;
while(n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println("Reverse of " + num + " is " + rev);
}
public void palindrome() {
int n = num, rev = 0;
while(n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
if(num == rev) System.out.println(num + " is Palindrome");
else System.out.println(num + " is not Palindrome");
}
public void prime() {
int count = 0;
for(int i = 1; i <= num; i++) {
if(num % i == 0) count++;
}
if(count == 2) System.out.println(num + " is Prime");
else System.out.println(num + " is not Prime");
}
}
public class Demo {
public static void main(String args[]) {
Calculate obj = new Calculate(121);
obj.reverse();
obj.palindrome();
obj.prime();
}
}
17. Create a class Vol having data members as r(radius), h(height). Use parameterised constructor to initialise the object. With the help of volume(); calculate and display the volume of cylinder (Hint : pr2h).
public class Vol {
double r, h;
public Vol(double radius, double height) {
r = radius;
h = height;
}
public void volume() {
double vol = 3.14159 * r * r * h;
System.out.println("Volume of cylinder is : " + vol);
}
public static void main(String args[]) {
Vol cylinder = new Vol(5.0, 10.0);
cylinder.volume();
}
}
18. A tech number has even number of digits. If the number is split in two equal halves, then the square of sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30+25)² = (55)² = 3025 is a tech number.
public class TechNumber {
public static void main(String args[]) {
System.out.println("All four digits tech numbers are:");
for(int i = 1000; i <= 9999; i++) {
int firstHalf = i / 100;
int secondHalf = i % 100;
int sum = firstHalf + secondHalf;
if((sum * sum) == i) {
System.out.println(i);
}
}
}
}