Let say I have:
class Superclass {
//fields...
methodA() {...}
methodB() {...}
...
}
class Subclass extends Superclass {
//fields...
methodA() {
// Here I need to call methods A and B from superclass:
// For this, I can use supper
super.methodA();
super.methodB();
// Or I have to instantiate the superclass and use the instance
Superclass superclass = new Superclass();
superclass.methodA();
superclass.methodB();
}
It works both ways, but I want to know which is better to use. Any of these ways is a bad programming technique? I hope you give me answer and arguments.
It works both ways, but I want to know which is better to use.
Well that entirely depends on what you're trying to achieve. If you want to create a new, entirely independent instance, do so. But it's more common that you want to use the superclass implementation of a method you're overriding on the same instance that the overridden method is currently executing on in which case you would use super.methodA()
.
In my experience, super
is most commonly used when overriding a method to do some subclass-specific work, call the superclass implementation, then do some more superclass-specific work. For example:
@Override public void add(Foo foo) {
doSomeSubclassSpecificValidation(foo);
super.add(foo);
doSomeSubclassSpecificBookKeeping();
}
In other words, even though you're overriding the method, you still want the "normal" behaviour - you just want some extra code to run as well. Or sometimes you want to run the superclass code conditionally, e.g. only if the input meets a certain criterion.
See more on this question at Stackoverflow