Java 2
Java 2
Objectives 3
Method Overriding 4
Rules 5
Example 7
Conclusion 8
Bibliography 8
pg. 2
TITLE
Method Overriding
OBJECTIVES
To develop a practice of learning new aspects of the subject & develop habit
of research to the subject.
pg. 3
METHOD OVERRIDING
Method Overriding is one of the way by which java achieve Run Time Polymorphism
In some cases, method overriding is mandatory - if you implement an interface, for example, you
must override its methods. Yet, in others, it is usually up to the programmer to decide whether
they will override some given methods or not.
Take a scenario where one extends a non-abstract class, for instance. The programmer is free (to
some extent) to choose methods to override from the superclass.
pg. 4
RULES FOR METHOD OVERRIDING
Another distinguishing difference between the two is how compilers treat them. Compilers choose
between overloaded methods when compiling and resolve overridden methods at runtime. That is
why overloading is also known as compile-time polymorphism. And we may also refer to
overriding as runtime polymorphism.
Still, overriding is a better than overloading when it comes to realizing polymorphism. With
overloading, you risk creating hard-to-read APIs. In contrast, overriding forces one to adopt class
hierarchies. These are especially useful because they force programmers to design for OOP.
pg. 5
In summary, overloading and overriding differ in these ways:
Writing two or more methods with the Writing two or more methods with
same name but different signatures is same name but different signatures is
overloading. Overriding.
Method return types can be same or Method return types should always be
different. same.
It is done when the programmer wants It is done when the programmer wants
to extend the available features. to provide different implementation for
the same feature.
pg. 6
METHOD OVERRIDING EXAMPLE
Class Vehicle {
Void run(){System.out.println(“Vehicle is Running”);}
}
OUTPUT :-
Bike is Running
pg. 8
CONCLUSION
Method overriding is integral to the presentation of Java's OOP muscle. It cements class hierarchies
by allowing subclasses to possess and even extend the capabilities of their super classes.
Still, most programmers encounter the feature only when implementing interfaces or extending
abstract classes. Non-mandatory overriding can improve a class' readability and consequent
usability.
Finally, because method overriding combines inheritance and polymorphism, it makes an excellent
tool for removing common code smells. Issues, such as, excessive conditionals and utility classes
could become less prevalent through wise use of overriding.
BIBLIOGRAPHY
pg. 9