Interview :: Core Java
Method Overloading | Method Overriding |
---|---|
1) Method overloading increases the readability of the program. | Method overriding provides the specific implementation of the method that is already provided by its superclass. |
2) Method overloading occurs within the class. | Method overriding occurs in two classes that have IS-A relationship between them. |
3) In this case, the parameters must be different. | In this case, the parameters must be the same. |
No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.
Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.
- The private can be changed to protected, public, or default.
- The protected can be changed to public or default.
- The default can be changed to public.
- The public will always remain public.
Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.
- If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
- If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.
Test it NowOutput: welcome to covariant return type
In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.
Test it NowOutput:Compile Time Error
If we change any method to a final method, we can't override it.
Test it NowOutput:Compile Time Error
If we make any class final, we can't inherit it into any of the subclasses.
Test it NowOutput:Compile Time Error
A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example: