Java Interview Question Set 10
Categories: Java 8(JDK1.8)
Can we assign the reference to this variable?
No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.
public class Test
{
public Test()
{
this = null;
System.out.println("Test class constructor called");
}
public static void main (String args[])
{
Test t = new Test();
}
}
Output
Test.java:5: error: cannot assign a value to final variable this
this = null;
^
1 error
Can this keyword be used to refer static members?
Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.
public class Test
{
static int i = 10;
public Test ()
{
System.out.println(this.i);
}
public static void main (String args[])
{
Test t = new Test();
}
}
Output
10
How can constructor chaining be done using this keyword?
Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.
What are the advantages of passing this into a method instead of the current class object itself?
As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.
a) this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
b) this can be used in the synchronized block.
What is the Inheritance?
Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.