Saturday 15 September 2018
Thursday 13 September 2018
What exactly does @Override do in Java?
@Override is annotation which is used to make compiler check all rules of overriding.If we don't write @Override over the method, then compiler will apply all overriding rules only if below three point are :
1. There are super class and sub class relation.
2. Method names are same.
3. Parameters are same.
But if we have written as @Override on sub class method, then compiler must apply all rules irrespective of above three points.
Below are the examples which will explain the use of @Override annotation.
1. Example without @Override annotation.
In the above example, there is no compile time and run time error. We will get output.
Child is called.
2. Example with @Override annotation.
In the above example, there is compile time error when we use @Override annotation that is we can not override private method.
1. There are super class and sub class relation.
2. Method names are same.
3. Parameters are same.
But if we have written as @Override on sub class method, then compiler must apply all rules irrespective of above three points.
Below are the examples which will explain the use of @Override annotation.
1. Example without @Override annotation.
In the above example, there is no compile time and run time error. We will get output.
Child is called.
2. Example with @Override annotation.
In the above example, there is compile time error when we use @Override annotation that is we can not override private method.
Sunday 9 September 2018
Can we Override static methods in Java
The process of implementing the super class method in sub class is called as method overriding. As per Java principle, classes are closed for modification. so if we want to modify a method in any class, changing existing method is not a good idea instead of that we should extend that class and override method in the child class.If we try to override the method which is static, compiler won't give any error but we will get the output that does not satisfy the definition of overriding.
For example, we have two classes Animal and Cat, in Animal class, we have declared two methods, one is static and another is not static and in Cat class, we have overridden the Animal class methods.
From the output of the below programs, we can say that static methods can not be overridden.
Output :
Animal class : The static method in Animal
Cat Class : The instance method in Cat
Subscribe to:
Posts (Atom)