Core Java Interview Question and Answer.
1) What are static blocks and static initializers in Java ?
Static blocks or static initializers are used to initialize static fields in java. we declare static blocks when we want to initialize static fields in our class. Static blocks gets executed exactly once when the class is loaded. Static blocks are executed even before the constructors are executed.
2) How to call one constructor from the other constructor ?
With in the same class if we want to call one constructor from other we use this() method.
Based on the number of parameters we pass appropriate this() method is called.
Restrictions for using this method :
a) This must be the first statement in the constructor.
b) We cannot use two this() methods in the constructor.
3) What is method overriding in java ?
If we have methods with same signature (same name, same signature, same return type) in super class and subclass then we say subclass method is overridden by superclass.
When to use overriding in java
If we want same method with different behavior in superclass and subclass then we go for overriding. When we call overridden method with subclass reference subclass method is called hiding the superclass method.
4) What is super keyword in java ?
Variables and methods of super class can be overridden in subclass . In case of overriding , a subclass object call its own variables and methods. Subclass cannot access the variables and methods of superclass because the overridden variables or methods hides the methods and variables of super class. But still java provides a way to access super class members even if its members are overridden. Super is used to access superclass variables, methods, constructors.
Super can be used in two forms :
a) First form is for calling super class constructor.
b) Second one is to call super class variables, methods. Super if present must be the first statement.
5) Difference between method overloading and method overriding in java ?
Method Overloading:
1)Method Overloading occurs within the same class.
2) Since it involves with only one class inheritance is not involved.
3)In overloading return type need not be the same.
4) Parameters must be different when we do overloading.
5) Static polymorphism can be achieved using method overloading.
6) In overloading one method can’t hide the another.
Method Overriding:
1) Method Overriding occurs between two classes superclass and subclass.
2) Since method overriding occurs between superclass and subclass inheritance is involved.
3) In overriding return type must be same.
4) Parameters must be same.
5) Dynamic polymorphism can be achieved using method overriding.
6) In overriding subclass method hides that of the superclass method.