[Method overriding in java] If the subclass has the same method as declared in the superclass, it's called Method Overriding in Java. In other words, if the subclass supplies the specific implementator of the method that was supplied by one of its parent classes, that method is overridden.
Method overriding in java used to obtain the polymorphism at runtime.
The problem is that you have to provide a specific implementation of the run () method in the subclass.
Question: Can we override the static method?
No, the static method can not be overwritten. This can be proved by the polymorphism at runtime, we will learn later.
Question: Why can not we override the static method?
Because the static method is bound to the class while the instance method is attached to the object. Static is owned by Class Area and instance owned by Heap Area.
Question: Can we override the main method?
No, because main is the static method.
To find out more about static keyword in java:
The use of method overriding in Java
Method overriding in java used to provide the specific implementator of a method that has been provided by its superclass.Method overriding in java used to obtain the polymorphism at runtime.
Rule for method overriding in Java
- The method must have the same name as the parent.
- The method must have the same parameters as in the superclass.
- Must be IS-A (inheritance).
The problem occurs if there is no method overriding in java
You follow the example below to understand the problem we might face if we do not use the method override.The problem is that you have to provide a specific implementation of the run () method in the subclass.
Example of method overriding in Java
In this example, we define the run method in the subclass as defined in the superclass, but it has a specific implementer. The name and parameters of the method are the same, and the relationship between the two classes is IS-A, so it's overriding the method.The real example of method overriding in Java
Suppose Bank is an object offering interest rates. But interest rates vary between banks. For example, Tcf, Wells Fargo and CreditOne can offer interest rates of 8%, 7% and 9%, respectively.Question: Can we override the static method?
No, the static method can not be overwritten. This can be proved by the polymorphism at runtime, we will learn later.
Question: Why can not we override the static method?
Because the static method is bound to the class while the instance method is attached to the object. Static is owned by Class Area and instance owned by Heap Area.
Question: Can we override the main method?
No, because main is the static method.
To find out more about static keyword in java:
Comments
Post a Comment