Java Interview Questions Set 6
Categories: Java 8(JDK1.8)
Is constructor inherited?
No, The constructor is not inherited.
Can you make a constructor final?
No, the constructor can't be final.
What do you understand by copy constructor in Java?
There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
a) By constructor
b) By assigning the values of one object into another
c) By clone() method of Object class
What are the differences between the constructors and methods?
There are many differences between constructors and methods. They are given below.
Java Constructor -Java Method
A constructor is used to initialize the state of an object.- A method is used to expose the behavior of an object.
A constructor must not have a return type. - A method must have a return type.
The constructor is invoked implicitly. - The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class. - The method is not provided by the compiler in any case.
The constructor name must be same as the class name. - The method name may or may not be same as class name.
What is the output of the following Java program?
public class Test
{
Test(int a, int b)
{
System.out.println("a = "+a+" b = "+b);
}
Test(int a, float b)
{
System.out.println("a = "+a+" b = "+b);
}
public static void main (String args[])
{
byte a = 10;
byte b = 15;
Test test = new Test(a,b);
}
}
The output of the following program is:
a = 10 b = 15
Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.