A constructor provides a convenient way to initialize a newly created object at the time of its creation. It is defined for a class and it is called automatically immediately after the creation of a new object, but before the new operator completes. All Although constructors look the same as methods, they are written by using the following conventions:

  1. A constructor is always given the name of the class in which it is defined.
  2. A constructor is always written without an explicit return type, not even void. This is because the implicit return type of a class constructor is the class itself.

  • Share/Bookmark

Constructors

If a class Student creates two student objects. Which of the following statements are true about its constructors?

A: The compiler can call to super() in any constructor that has a call to this().
B: If a constructor is not declared in the code, a default constructor will be automatically generated by the compiler.
C: Constructors can be overridden.
D: The compiler cannot call to super() in any constructor that has a call to this()

ANSWERS:

  • Share/Bookmark

class box
{
int height;
int weight;

box( int a, int b)
{
height=a;
weight=b;
System.out.println(height);
System.out.println(weight);
}

}

class Box2
{
public static void main(String args[])
{
Box2 b2=new box();
}
}

  • Share/Bookmark

What is a constructor?

A constructor provides a convenient way to initialize a newly created object at the time of its creation. A constructor is automatically called emmediately after the creation of a new object, but before the new operator completes. All Java classes must have at least one constructor, either explicitly declared in the class or an implicit default constructor. They are typically used to create an object that is an instance of a class. It is written by using the following general syntax:

[access modifier] class name([formal parameter list]) [throws clause] {
// Body of the constructor
}

  • Share/Bookmark