As far as I understand, this can be used inside a class to call a method available in any of its superclass as the compiler will look for the method in its superclasses if it's not available in the (sub)class. Basically just like using a super.
So I was wondering, which is the better way of doing things? Is there a general rule of thumb for sing either?
QUESTION:
When the method in question is not coded i.e only available via inheritance from its super class) in the (sub)class, they basically do the same thing right? In that case, is there a reason to pick one over the other?
super.methodAvailableInSuper();
or
this.methodAvailableInSuper();
MORE CLARIFICATION
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
They're not equivalent, so your question isn't meaningful.
this.method() will invoke the most-derived override of method(), including in any derived classes that this object may be an instance of
super.method() will invoke the base class's implementation of method(), or whatever implementation it inherited if it doesn't provide an implementation itself.
You should use whichever one does exactly what you want. It's not just an aesthetic choice, or a question of 'good practice'.
EDIT Re your edited edit:
When the method in question is not available in base class, they basically do the same thing right?
Wrong. super always calls a method in the base class or one of its parents. this calls the most-derived override. You would write super if you definitely didn't want to call any future implementation in any future derived class, and you would write this, or nothing, if you did want to call such an implementation if it exists when the call is made. Which is not something you can know when coding.
This is not a question of "best practice" since these keywords are very different.
When you call super.methodAvailableInSuper(); then all parent classes are searched for this method at runtime. If this method exists in the current class or any subclass, this method wont be executed.
You can use this, if you want to call the super implementation of an overriden method without cousing an endless loop.
The keyword this calls the method on the current object. Thus the normal execution of methods will be performed.
See also:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
Related
This message pertains strictly to Java. If a method is in a superclass there are two ways the method could be called:
foo();
super.foo();
Is there any harm in always doing the latter? As a coding style I prefer the latter because it's clear at a glance where the method call is coming from. Are there any circumstances where 'super' is going to be non-existent or not do what I think it would do?
I think the only harm you may have is when you want to use polymorphism so, if you call foo() and some subclass overrides foo, then the effect would be different than if you call super.foo(), basically, it depends on how you are designing the code and for what purpose.
Hope this makes it clear.
As a general rule, you should only use super.foo() inside your class foo() method. Doing otherwise, in general, goes against OOP thinking.
because it's clear at a glance where the method call is coming from
In OOP you should'n want to know where the method call "comes from". If your program (or your thinking) is depending on that, you are in potential trouble (and will probably be in actual trouble when someone decides to override the method). The method myobject.foo() must be seen from the outside as the method of the myobject's class; it should not matter if that method is implemented actually in the concrete class of its parent.
I would say there is more harm in doing the former as it's not clear that it's a method of the superclass.
Yeah this basically breaks the inheritance chain.
You don't allow the inheritance mechanism to choose what function to use even in classes derived from this one.
The point of super.foo() is to allow you to specify only when it is needed and you know no other behavior will be good.
If you do not want to explicitly avoid using an overriding method in the subclass then you should not use super.
Always using super might cause trouble if later on someone wants to override the method in the subclass.
That's a preferable way if you intend to call the method on the super class, instead of calling foo() without super.. If anyone does overwrite foo() in the subclass the super call does call the same method as before, but omiting super will now call the overwritten method. It depends on what you intent with that method call.
It depends.
If foo() is declared as final, it will make no difference at all. If foo() is not declared as final, then a subclass could override the declaration of foo() in your superclass and completely change the expected behaviour.
If you make your own class final, you can prevent it from being sub-classed, and be certain the original intent is preserved.
I would be say that this might indicate that you should think over you design again.
If you are always calling the functionality by super.foo() then you block yourself from overriding the function later, and if you don't want to have the ability to override the function, then maybe you shouldn't use inheritance as a method for accessing this functionality.
One design principle that I have heard banded about is "favour composition over inheritance", the reason for this is that your code becomes more flexible with composition rather than inheritance. And if you don't gain the positive aspects of inheritance (being able to override the function) then maybe it's wiser to not use inheritance.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does this() and super() have to be the first statement in a constructor?
I just learned that at school, but the teacher doesn't know why.
I can think of some good reasons, but I think there are cases when the initializing can be done later in the constructor- before you use the variables form the mother class, for example. OK, the variables should be initialized from the start, but that's not always necessary.
I"m guessing there are a more reasons for that why must super() be placed in the first line of the constructor.
So, why must I write super() in the first line of the constructor, when I'm inheriting a class?
The class you're inheriting from needs to be able to complete its construction, before you have start working on your own class.
Without doing this you could do lots of "bad" things, e.g.
Pass this to another method somewhere else, which uses the base class, before its constructor has run. That would break lots of assumptions
Call polymorphic functions that haven't been "set up" correctly yet. As well as anything done by the class itself the implementation possibly uses the constructor call to handle implementation internals too.
Accessing an object before it's been constructed is bad, in the same way that fried chicken "is-a" chicken you really don't want to access (eat) that chicken before it's been fried.
Access protected/public member variables of the base class which the base class was trying to promise would always be initialised to some state.
It's perfectly reasonable for a class to make a promise that any instances of it will always be in some given state. If you get a chance to do things before the constructor has been called then there's no way to honour promises like that. Essentially the "is-a" relationship wouldn't actually hold if the thing that it "is" isn't actually that thing yet!
In addition to awoodlands answer: You dont have to write super(), since the Java-Compiler will automatically call all the default constructors up the hierarchy.
Exception: If you dont have a default constructor in the base class, you would have to call your custom constructor using super(ConstructorArgs args).
I am wondering if there is any way to achieve the following.
Find a method using reflection (done)
Change the method access modifier to to public and static. (How?)
execute this method without having any existing instance (How?)
Does reflection has any option to do this?
No, this is completely impossible and makes no sense whatsoever. An instance method has access to (and typically uses) instance variables. What should e.g. a typical set or get method that has been "made static" possibly do?
This doesn't make any sense. A non-static method is non-static for a reason, in that it needs to access member data specific to a particular instance of the class. How would you convert that to static?
Even if you used tools that let you change a class (like BCEL), you still wouldn't have achieved anything, because (all minor caveats aside) the moment you change a method from instance method to static, all code calling it will throw a NoSuchMethodError. The reason being that invoking a static/instance method use two different opcodes.
No. You can't change a class with reflection. You can just inspect it.
I don't think it's possible.
If your method uses a 'this' reference, that would be an undefined behaviour.
As all said this is bad and should not be done.
But again if you have to achieve this and you have already given the reason so I might like to try something different to achieve this.
I might create a singleton class and give a static method (facade) to access the required API method and always make sure that all other classes use this singleton class method to access the API method.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When do you use Java's #Override annotation and why?
I wonder what the functionality of adding #Override in front of the code we would like to override is. I have done with and without it, and it seemed that everything was just going well (at least, for me).
It is not necessary, but it is highly recommended. It keeps you from shooting yourself in the foot. It helps prevent the case when you write a function that you think overrides another one but you misspelled something and you get completely unexpected behavior.
what the functionality of adding #Override
It lets the compiler double-check for you when you say (by annotating) that a specified method is supposed to override a superclass method (or implement an interface method in Java 6 or later). If the method does not, in fact, override a superclass method (or implement an interface method), the compiler will flag this as an error. This often indicates that you have a typo in the method name or made a mistake in the method signature.
Do we really need #Override
Need it? Absolutely not, but its such a cheap way to
conveys explicitly to human reader that this is an overriding method, and
catches a bug at compile time that could take at least a few brain cycles to catch at run-time once you even know to look for it
... and even cheaper when your IDE is helping you include it ...
It's recommended since it helps to manage consistence. Imagine someone will change the name of superclass method (and only there, without performing name-changes in classes depending on it which is quite hypothetical :) ), then you will be the first one to know due to compilation errors.
The only difference would be that if you annotate a method with #Override and you are not overriding anything, the compiler will complaint.
Check When do you use javas override annotation and why?
It's helped me a good couple of times to avoid spelling errors / case differences in method names. Without it it's one of these annoying bugs that can take ages to track down.
It doesn't add any functional difference, but telling the compiler you think you're overriding a method so it can complain if you're not is very useful when you've screwed up somewhere!
It's highly recommended to use it since it increase undersatadability of ur code and help others to maintain ur code too .
Personally I dont think it is useful except for IDE's that do the compile-time error checking, but that is my opinion. Reason: suppose you have
Class A {
methodName() { System.out.println ("A"); }
}
class B extends A {
methodName() { System.out.println ("B"); }
}
At runtime, you will probably call B.methodName() - it doesnt matter to B whether B.methodName() overrides the same name of class A(). To class B, it shouldn't even matter if the superclass (A) implements methodName(). What I mean is that inheritance is a one-way street - You cannot un-inherit something by using a #override - all the compiler can check is if there is a method with the same signature in the superclass - which will not be used anyways.
For the other answers, if someone edits A.java to delete or rename methodName() or change its signature, you can still call B.methodName() without a problem, but only if you do not use that #override. I think this is also why it is not a part of the Java language.
NO!
If you find it useful, you need a real IDE, or learn how to use it.
This is a question about coding style and recommended practices:
As explained in the answers to the question unnecessary to put super() in constructor?, if you write a constructor for a class that is supposed to use the default (no-arg) constructor from the superclass, you may call super() at the beginning of your constructor:
public MyClass(int parm){
super(); // leaving this out makes no difference
// do stuff...
}
but you can also omit the call; the compiler will in both cases act as if the super() call were there.
So then, do you put the call into your constructors or not?
On the one hand, one might argue that including the super() makes things more explicit. OTOH, I always dislike writing redundant code, so personally I tend to leave it out; I do however regularly see it in code from others.
What are your experiences? Did you have problems with one or the other approach? Do you have coding guidelines which prescribe one approach?
BTW: A related question (just for reference):
Is there a reason to explicitly code a default constructor when there are no other constructors?
I don't write the super() call for the same reason I don't write unnecessary casts:
It adds noise to the code without providing any additional information (neither to the compiler nor to the developer reading my code).
The default settings of some versions of some IDEs generate it automatically, so that's one reason you might be seeing it.
Whether to write it or not depends on who will be reading it. I prefer not to add it, but if you are not certain that team members understand what the compiler does, and how object construction proceeds, you may add it "just in case".
I don't, but the argument given to me for doing this while at university was that it makes things more explicit, so you don't 'forget' that a superclass constructor is being called.
I just don't see the need tho.
I use the super() only when the constructor super() needs parameters.
What are your experiences? Did you
have problems with one or the other
approach?
I never called the default constructor (explicit) and never faced any problems
I never add it and I was deeply shocked when a colleague didn't understand that there was an implicit call made to the super class so perhaps I should start doing it.
Advantage: Anyone reading your code knows that you really want to call the default constructor, you did not leave the call out by mistake.
Disadvantage: You clutter your code with unimportant information.
Usually, if a language lets you omit some instruction, it is not bad style doing so. I think it is a question of weighing the pros and cons. For instance, explicitly writing super() when your constructor has parameters and the base class also has parametered constructors available may be a good idea.
I actually put the super() call in as I find it to be a helpful memory aide. When I have written a piece of code a few months ago and return to it, the super() reminds me when I am looking at the constructor that the class I wrote inherits from something.
I try to avoid writing code where calling super() is necessary, because I prefer composition over inheritance.
If I have to derive from another class, I try to put both behind an own interface and pass one of them to the other as a dependency.
If I have a lib class, however, which I cannot give an extra dependency, the first thing I try is to use a decorator.
If this doesn't work, and I have to derive from an implementation, I think it doesn't matter whether to write super() or not, since it happens so rarely ;)
So, all in all, I think this question is pointless.