-
Static blocks or static initializers are used to initalize static fields in java. we declare static blocks when we want to intialize static fields in our class. Stati blocks gets executed exactly once when the class is loaded .Static blocks are executed even before the constructors are executed.
-
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 :
- this must be the first statement in the constructor.
- we cannot use two this() methods in the constructor.
-
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 behaviour 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.
-
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 :
- First form is for calling super class constructor.
- Second one is to call super class variables,methods.
Super if present must be the first statement.
| Method Overloading | Method Overriding |
|---|---|
| Method Overloading occurs with in the same class | Method Overriding occurs between two classes superclass and subclass |
| Since it involves with only one class inheritance is not involved | Since method overriding occurs between superclass and subclass inheritance is involved. |
| In overloading return type need not be the same | In Overriding return type must be same |
| Parameters must be different when we do overloading | Parameters must be same |
| Static polymorphism can be acheived using method overloading | Dynamic polymorphism can be acheived using method overriding. |
| In overloading one method can't hide the another | In overriding subclass method hides that of the superclass method |
