KnowledgeBoat Logo
OPEN IN APP

Chapter 4

Constructors

Class 10 - Sumita Arora ICSE Computer Applications with BlueJ



Objective Type Questions

Question 1

A member function having the same name as that of its class is called constructor function.

Question 2

A constructor function has no return type.

Question 3

A private constructor allows object creation only inside member functions.

Question 4

A non-parameterized constructor takes no arguments.

Question 5

A parameterized constructor creates objects through values passed to it.

Question 6

The keyword this refers to current object.
Or
Name the Java keyword that stores the address of the currently-calling object.

Answer

'this' keyword stores the address of the currently-calling object.

Question 7

Many constructor definitions in the same class is known as constructor overloading.

Assignment Questions

Question 1

What is a constructor ? What does it do ?

Answer

A constructor is a member function with the same name as that of its class but no return type.

A constructor is used to initialize the objects of that class type with legal initial values.

Question 2

What is that class called which does not have a public constructor ?

Answer

A class which does not have a public constructor is called a private class as only the member functions may declare objects of the class.

Question 3

When is a constructor automatically invoked ?

Answer

A constructor is automatically invoked when the object of a class is created.

Question 4

Write two characteristics of a constructor.

Answer

Two characteristics of a constructor are:

  1. It has the same name as that of its class.
  2. It has no return type, not even void.

Question 5

Write a class specifier (along with its constructor) that creates a class student having two private data members : rollno and grade and two public functions init( ) and display( ).
(Do not write full definitions of member functions except for constructor).

Answer

class student
{
    private int rollno;
    private char grade;

    public student()    {
        rollno = 0;
        grade = '\0';
    }

    public student(int roll, char g)
    {
        rollno = roll;
        grade = g;
    }

    public void init()  {}
    
    public void display()   {}
}

Question 6

Can you think of the benefits of a private class if any ? What are they ?

Answer

The benefits of a private class (i.e., a class with a private constructor) are:

  1. Controlled object creation — By making the constructor private, we can control the number of objects of a class that can be created. We can also enforce certain rules or constraints on how the object is created and used.
  2. Better memory management — By limiting the number of objects of a class that can be created, we can reduce memory usage and improve performance.

Question 7

Here is a skeleton definition of a class :

class Sample
{
    int i;
    char c;
    float f;
    :
    //public members
    :
}

Implement the constructor.

Answer

The constructor of the class is given below:

public Sample(int a, char b, float c)
{
    i = a;
    c = b;
    f = c;
}

Question 8

Define a constructor function for a Date class that initializes the Date objects with given initial values. In case initial values are not provided, it should initialize the object with default values.

Answer

public Date()
{
    day = 1;
    month = 1;
    year = 1970;
}
public Date(int d, int m, int y)
{
    day = d;
    month = m;
    year = y;
}

Question 9

What condition(s) a function must specify in order to create objects of a class ?

Answer

Every time an object is created, the constructor is automatically invoked. If the function creating the object, does not have access privilege for the constructor, it cannot be invoked for that function. Thus, the object cannot be created by such function.

Therefore, it is essential for a function to have access privilege for the constructor in order to create objects of a class.

Question 10

Constructor functions obey the usual access rules. What does this statement mean ?

Answer

Constructor functions obey the usual access rules. It means that a private or protected constructor is not available to the non-member functions.

With a private or protected constructor, one cannot create an object of the same class in a non-member function. Only the member functions of that class can create an object of the same class and invoke the constructor.

Question 11

How are parameterized constructors different from non-parameterized constructors?

Answer

Parameterised constructorNon-parameterised constructor
Parameterised constructor receives parameters and uses them to initialise the object's member variables.Non-parameterised constructor does not accept parameters and initialises the object's member variables with default values.
Parameterised constructors need to be explicitly defined for the class. They are never created automatically by the compiler.Non-parameterised constructors are considered default constructors. If no constructor is explicitly defined, then the compiler automatically creates a non-parameterized constructor.
For example,
Test(int x, int y)
{
a = x;
b = y;
}
For example,
Test()
{
a = 10;
b = 5;
}

Question 12

What are benefits/drawbacks of temporary instances ?

Answer

The benefit of temporary instances is that they live in the memory as long as they are being used or referenced in an expression and after this, they are deleted by the compiler. The memory is freed as soon as they are deleted rather than staying in the memory till the program completes execution.

The drawback of temporary instances is that they are anonymous i.e., they do not bear a name. Thus, they cannot be reused in a program.

Question 13

How do we invoke a constructor ?

Answer

A constructor is invoked automatically when an object of a class is created. The constructor is called using the new keyword followed by the name of the class and a set of parentheses. If the constructor requires arguments, the arguments are passed inside the parentheses.

For example, suppose we have a class named Person with a parameterized constructor that takes two arguments name and age. To create an object of this class and invoke the constructor, we would use the following code:

Person personObj = new Person("John", 30);

Question 14

How can objects be initialized with desired values at the time of object creation ?

Answer

Objects can be initialized with desired values at the time of object creation by using parameterized constructor and passing the desired values as arguments at the time of creation of object.

Question 15

When a compiler can automatically generate a constructor if it is not defined then why is it considered that writing constructors for a class is a good practice ?

Answer

Writing constructors for a class is considered a good practice for the following reasons:

  1. Control over object creation — By writing our own constructors, we can control how objects of our class are created and initialised. It ensures initialising member variables to specific values and executing certain initialisation logic before the object is used.
  2. Parameter validation — We can prevent runtime errors and bugs by validating input parameters and ensuring only valid objects are created.
  3. Flexibility — Multiple constructors allows users of the class to create objects in different ways, depending on their needs. This makes the class more flexible and easier to use.

Question 16

'Accessibility of a constructor greatly affects the scope and visibility of their class.' Elaborate this statement.

Answer

Every time an object is created, it is automatically initialised by the constructor of the class. Therefore, it is very much necessary for the constructor of a class to be accessible by the function in which the object is created. If the constructor of a class is declared 'private' or 'protected', then the scope and visibility of the constructor (and the class) is defined by the rules of the access specifier.

In such a case, a function not having access to constructor of a class cannot declare and use objects of that class. Hence, accessibility of a constructor greatly affects the scope and visibility of their class.

Question 17

List some of the special properties of the constructor functions.

Answer

Some of the special properties of the constructor functions are as follows:

  1. It has the same name as that of its class.
  2. It doesn't have any return type, not even void.
  3. It adheres to the rules of access specifiers.
  4. It can be parameterized or non-parameterized.
  5. It is used to create and initialize objects from a class.
  6. It can be overloaded to provide multiple ways of creating objects with different initialisation parameters
  7. It is always called implicitly when an object is created using the new keyword.

Question 18

What is a parameterized constructor ? How is it useful ?

Answer

Parameterized constructors are the constructors that receive parameters and initialize objects with received values. For example:

class XYZ
{
    private int i; 
    private float j;

    XYZ(int a, float b)     //parameterized constructor
    {	
        i = a ;
        j = b;
    }
    :
    //other  members
    :
}

Parameterized constructors are useful in the following ways:

  1. Control over object creation — By writing our own constructors, we can control how objects of our class are created and initialised. It ensures initialising member variables to specific values and executing certain initialisation logic before the object is used.
  2. Parameter validation — We can prevent runtime errors and bugs by validating input parameters and ensuring only valid objects are created.

Question 19

Design a class to represent a bank account. Include the following members:

Data members

  1. Name of the depositor
  2. Account number
  3. Type of account
  4. Balance amount in the account

Methods

  1. To assign initial values
  2. To deposit an amount
  3. To withdraw an amount after checking balance
  4. To display the name and balance
  5. Do write proper constructor functions

Answer

class BankAccount
{
    private String name; 
    private long accno;
    private char type;
    private double bal;

    BankAccount()   {
        name = "";
        accno = 0;
        type = '\0';
        bal = 0.0d;
    }
    BankAccount(String n, long accnumber, char t, double b)   {
        name = n;
        accno = accnumber;
        type = t;
        bal = b;
    }

    public void deposit(double amt)   {
        bal = bal + amt;
        System.out.println("Amount deposited: Rs. " + amt);
        System.out.println("Balance: Rs. " + bal);
    }

    public void withdraw(double amt)    {
        if(amt <= bal)  {
            bal = bal - amt;
            System.out.println("Amount withdrawn: Rs. " + amt);
            System.out.println("Balance: Rs. " + bal);
        }
        else {
            System.out.println("Insufficient Balance");
        }
    }
    
    public void display()
    {
        System.out.println("Name: " + name);
        System.out.println("Balance: Rs. " + bal);
    }
}
PrevNext