Java Interview Questions Set 9
Categories: Java 8(JDK1.8)
Can we make constructors static?
As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.
Can we make the abstract methods static in Java?
In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.
Can we declare the static variables and methods in an abstract class?
Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.
abstract class Test
{
static int i = 102;
static void TestMethod()
{
System.out.println("hi !! I am good !!");
}
}
public class TestClass extends Test
{
public static void main (String args[])
{
Test.TestMethod();
System.out.println("i = "+Test.i);
}
}
What is this keyword in java?
The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.
What are the main uses of this keyword?
There are the following uses of this keyword.
a) this can be used to refer to the current class instance variable.
b) this can be used to invoke current class method (implicitly)
c) this() can be used to invoke the current class constructor.
d) this can be passed as an argument in the method call.
e) this can be passed as an argument in the constructor call.
f) this can be used to return the current class instance from the method.