E.g. :
public class ClassA extends ClassB {
public void run() {
super.execute();
...................
Method execute exists only in ClassB.
Does it make sense to use:
super.execute();
may be enough:
execute();
?
Thanks.
Since the execute() method is not overridden in ClassA, execute() is equivalent to super.execute().
I see absolutely no "documentational" benefit of highlighting the fact that the method is defined in the super class. Thus personally I would write execute() (unless there were strong reasons to call super.execute() if ClassA was ever modified to override execute).
Reasons:
Predictability (safety?) - if one day somebody implements ClassA.execute(), the code will work differently. This is also the case even is somebody subclasses ClassA and overrides execute(), leaving ClassA intact.
Performance - super call may be faster than virtual. super is implemented using invokespecial (single dispatch, just like private method), while ordinary call to non-private method uses double dispatch (virtual call). This is a weak advantage in modern JVMs.
Bottom line: if ClassB.execute() is final, using super has no sense.
No, simply call execute(). Since the method is not overridden, super.execute() would have the same result as this.execute(), which is the same as execute().
It's ok to call super.
If you want to ensure you are calling the parent class method, then use super. So if you introduce the method later in ClassA, code will not break.
By the contrary, if you want to call execute whatever it is... don't use super.
super reserved word exist normally to call to the overriden method from the overrider one.
According to the java syntax this is correct. but when it comes to the real software engineering concepts this wont make any sense at all.I would suggest you to override run method in class B and then call the super class method inside that. After calling the supper class method you can construct you specific logic for the subclass. Its like you have some generic functionalities in the parent method and specific functionalities (in additions to what parent has) in sub class.
Related
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.
super.methodA();
Superclass superclass = new Superclass();
superclass.methodA();
These two calls of methodA work on different instances, so they are completely different. super.methodA() executes methodA on the current instance. superclass.methodA() executes methodA on a new instance of Superclass which is not related to the current instance.
You would almost always use the first option. As for the second option, It doesn't make sense to create a new instance, call a method on that instance and then never do anything with that instance again.
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.
It's totally different.
super.methodA() will call methodA() in the left circle, while creating a new superclass and calling that methodA() will first create the right circle, and then call methods from it.
With above answers, you must have understood that basically you are calling same method of same class but on two different objects so it all depends as what you are trying to achieve ( On which object you plan to call those methods ). As you know, call to same methods of same class but on different instances are not the same. "super" object is parent of "this" object and that super object was created implicitly when you instantiated Subclass so as per your example code, both are NOT SAME but for simple cases,output might be same. Go one more level up and see if it looks different to you from client code ( try writing calling code of Subclass ).
Lets think about Asynctask class.
It has overrideable methods such as onPreExecute,onProgressUpdate etc.
Compiler does not give error if i dont add super.'method-name' etc. So should i do it or not? What is the benefit of calling (or not calling) super methods when we dont have to call
When we think of extending EditText class, after your customization you need to call super constructor for sure.
NOTE: I am talking about optional super calls.
in general, and as a rule in object oriented programming: unless you have a good reason to break it, and you know exactly what's the super class method implementation all about, you should always call the super class methods.
in the specific case of AsyncTask - it is not required to call the super class method, simply because it does not doing any code.
opposite example: if you will not call the super methods of an Activity callbacks such as onCreate() and onDestroy() you will break entirely the activity, and probably nothing will work. that's because the super class implementation of this methods doing tons of stuff required from each activity.
so the conclusion is that if you are not the writer of the base class - look for documentation providing any hints about methods you which to override in order know how, and if at all you should call the super class methods.
As they are empty methods you do not have to call them. They are just there for you to use for overriding.
If you don't call the superclass's method, then...the superclass's method doesn't get called. Whether that's a problem depends entirely on what the superclass method does. If it's optional, as you say, then call it if you need to (e.g., your logic requires whatever it does) and don't call it if you don't.
If the superclass's method is empty, the only reason for coding the call to it would be if you rebased your class. E.g., suppose you had A as a base with an empty foo method, and B derived from it (class B extends A). Later, you want to be able to change it to class B extends SpecialA where SpecialA is a special version of A where foo does something. If you've left the supercall out of B's foo, you'll have to remember to add it. If you included it in the first place, you won't have to remember to add it.
(The only supercall that has to happen is a call to the superclass's constructor when constructing the object, but if you leave that out, the compiler will supply a call to the zero-args version [e.g., super()]. But that's a constructor, not a method.)
I have a class called Base which has a method called execute(). There are about 100 classes which derive from this base class and provide their own implementation of execute(). Now, I have some common logic which I want to put in Base.SomeMethod(). This method needs to be called at the end of execute(). My question whether it is possible to call this without changing each and every derived class's execute() method?
public class Base {
public final void execute() {
doExecute();
someMethod();
}
protected abstract void doExecute();
public void someMethod() {
}
}
This solution prevents the super code smell.
Yes, but you have to change the callers then. Callers will have to call a doExecute() (find a better name for it though) method, which you define in your base class as final, and which calls execute(), then the common code.
Another option is aspect-oriented programming, but I wouldn't recommend it for this purpose, that is, to "hack" code.
The question is: why is changing the name of a method in a 100 or so classes such a problem? It's a click of the mouse with an IDE.
Not that I'm aware of. Next time you should consider that you might want to add some common action for all extended classes, and call for super.execute()!
Only by using something that instruments your code; this isn't possible with pure Java.
Let me state your problem as i understand : Animal class has Breath() method which has implementation and due to inheritance all the subclasses has this member and unless there is very different way of breathing nobody will override.
Now at the end of Breath method you want to call CloseEyes() method of animal class and may be that is true that some or all of the subclasses overrides CloseEyes() method.
So your problem : Everytime any animal breath you want to them to CloseEyes but from Animal class and not from the derived classes.
If there are already CloseEyes() methods in many derived classes then you are actually doing something wrong in calling base class's CloseEyes().
If you still want only base class's method to be called then why do you need same method name- you just say AnimalEyeClose() , make it private and have it in Animal class.
Suppose that I have this method:
public void callDo(FeelFreeToExtend ext){
ext.do()
}
Where FeelFreeToExtend is this:
public class FeelFreeToExtend {
public void do(){
System.out.println("DO");
}
}
Now I know that someone could override the do method but is there a way that I can explicitly call the do method in the FeelFreeToExtend class? I don't think that this would ever be a great idea however it is still interesting.
No, it is not possible without changing the bytecode/code of all the callers. If you want to always call the FeelFreeToExtend.do() make the method final.
Append the non-access qualifier "final" to the method (make the method final), this will stop the method from being overridden and hence this version of the method will be called always from any of the subclasses.
Secondly, if you just want to access a super class method from a derived class even if the super class method has been overridden then just call the method by appending "super." before the method call.For eg. to call the method "display" of a super class from a subclass, use super.display(). (This assumes that you are the one coding the sub class)
Actually what Peter says is not completely correct: in fact it is possible to execute an overridden method using JNI (http://java.sun.com/docs/books/jni/html/fldmeth.html#26109). In JNI there are method called CallNonvirtual<Type>Method allowing exactly that.
Application servers or frameworks could be shipped with a small JNI utility to allow this kind of features...
Without JNI I don't think this is possible.
This question occured to me while programming a Android application,
but it seems to be a general programming question more.
The situation is, I am extending (subclass-ing) an class from a library, and overriding a method. how do I know if I should invoke the method of super-class? and when? (in the beginning of the overridden method or in the end?)
For example, I am overriding the method "public boolean onCreateOptionsMenu(Menu menu)" from class "Activity" in Android platform. And I saw someone write "return super.onCreateOptionsMenu(menu)" in the end of the method, in an example. But how do I know it should be done this way? and it is correct or not? what's the difference if I begin my method with "super.onCreateOptionsMenu(menu)"?
BR,
Henry
I don't think you can answer this question in the abstract: it depends on the behavior of the superclass method you're overriding.
Depending on circumstances, it may be appropriate to:
call super first
call super last
handle some cases yourself (customizations), call super for the rest
never call super
Hopefully the documentation for the particular class you're overriding will tell you if/when it's necessary to call super.
Unfortunately, there is no rule for this. You need to refer to the API docs and call super if the docs say you need to.
One hint as to whether you'll probably need to or not in Android's case is if the method you're overriding is one of the lifecycle methods. In this case, you can be fairly certain that you need to call super.
These are valid questions, but unfortunately there is no general rule to follow here.
Whether or not you need to call super method depends on the fact if the super method does something that needs to be done. In other words: are you extending or replacing the overridden method? A good API documentation of the class should give you the answer. Also, libraries often follow some conventions to make it clear how to use them.
The answer to the question where to place the super call depends on when you want to execute you’re extension. Does it need to run before or after the super method? Most often you first call super and then do something extra. But if you need to prepare something for the super method, for example modifying some object state or manipulate the arguments, you place the code before the super call. Again, the API documentation should give you the answer here.
Android will in most of the cases cause a exception if you forget to call super.
I would trust that you don't have to call super if you don't do it and it doesn't throw.
In the google groups discussions some best practices for the lifecycle methods evolved(They are not officially backed by data but used by many programmers):
If you are in a creating method like
onCreate, onResume, etc. call super
as the first statement. Thus you can be sure that everything that has to be prepared from the superclass is prepared.
If you are in a closing method like onSaveInstanceState, onPause call super last. Now you could be sure that nothing gets removed or changed to a bad state before you got everything done.
You are not required to call the super.method(), you call it only when you need it where you need it.
When you override a method in a child class then it depends on the type of the instance on which you are calling that method.
for example:
Class Animal{
public eat(){
//..
}
}
Class Dog extends Animal{
public eat(){
//..
}
}
now if you say new Dog().eat()
it executes Dog's eat method.
if you say new Animal().eat()
it executes Animal's eat method.
And you may have code like this
Animal a = new Dog();
a.eat();
which again executes the Dog's eat method as the actual instance is of the type Dog.