0
Why do we use overriding in our code?
2 ответов
0
Sometimes we want to use a similar method in an inherited class although the methods have the same name.
The inherited method might have some enhanced features that the parent class lacks.
Example:
class A {
public void someMethod() {
//This method might do something boring
}
}
class B extends class A {
public void someMethod() {
/*This method overrides the method
in class A. Also we can do additional
things or completely different things than
the method in class A. If this method does
the same thing as the one in class A, then
we simply have duplicate code, a waste of
space. There's no need to override a method
if you're only doing the same thing. */
}
}
0
super classes are too general and subclasses are too specific. It is good to have a common generic method in superclass that most subclasses would use it instead of defining the same method (with same functionality) in the subclass. Lesser code to write with more usability. But whenever different functionality is needed, the method need to be overridden. Maybe a different method name can be chosen instead of overriding, but even that makes things complicated in the long run, remembering many names for the not so different functionality. Just my opinion.