Java Interview Question Set 13
Categories: Java 8(JDK1.8)
What are the main uses of the super keyword?
There are the following uses of super keyword.
a) super can be used to refer to the immediate parent class instance variable.
b) super can be used to invoke the immediate parent class method.
c) super() can be used to invoke immediate parent class constructor.
What are the differences between this and super keyword?
There are the following differences between this and super keyword.
a) The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
b) The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
c) The super and this must be the first statement inside constructor otherwise the compiler will throw an error.
What is the output of the following Java program?
class Person
{
public Person()
{
System.out.println("Person class constructor called");
}
}
public class Employee extends Person
{
public Employee()
{
System.out.println("Employee class constructor called");
}
public static void main (String args[])
{
Employee e = new Employee();
}
}
Output
Person class constructor called
Employee class constructor called
Can you use this() and super() both in a constructor?
No, because this() and super() must be the first statement in the class constructor.
What is object cloning?
The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
protected Object clone() throws CloneNotSupportedException