Constructor Questions Answer
Constructor Questions Answer
1. Define Constructor?
A constructor in Java is a special method that is used to initialize
objects/variables.
The constructor is called when an object of a class is created.
In Java, constructor role is only initializing object , and new keyword role
is crating object.
No. You cannot call a sub class constructor from a super class
constructor.
When you set a method as static, it means “The Method belong to class
and not to any particular object” but a constructor is always invoked with
respect to an object, so it makes no sense for a constructor to be static.
When you set a method as abstract, then “The method doesn’t or cannot
have body”. A constructor will be automatically called when object is
created. It cannot lack a body moreover an abstract constructor could
never be implemented.
When you set a method as final, then” The method cannot be overridden
by any class”. A constructor is not inherited, so there is no need
for declaring it as final.
i. Default Constructor
If programmer has declared the constructor in the class then compiler will
not provided default constructor.
}
public static void main(String[] args)
{
sample s = new sample();
s.display();
}
public void display()
{
System.out.println("Calling non-static
method..");
System.out.println("Roll no is:"+roll_no);
System.out.println("Name is:"+name);
}
}
class Temp
{
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}