How Does Java Overriding Work - java

I have a stupid confusion, when we override the parent class method then does this derived overridden method still hold the code of parent class method, or it is a new fresh method which we can define?

Read this article to get concept clear. http://docs.oracle.com/javase/tutorial/java/IandI/override.html
Generally we do when we want to extend the method of super class or to want to change the complete logic.
For ex: Super class have sorting method which use bubble sort.
In Derived class you want to take same method but want to implement quick sort. Then we do overriding.
Second
If you want to execute super class method first then your sub class overriden method logic then we use super.methodname().
Last to point of your question If you override the method and not called super class method like super.method() then its not mean its fresh method. Its means I already explain the sort example.

what happens is exactly what's written in the annotation.
you override the method and instead of running the parent code for the method, it runs the current class's code

Related

Reference overridden method in supertype constructor

I'm trying to find a solution for a project assignment. Basically I have created a class which is derivative of another abstract class. In it's construction I'm trying to call the supertype constructor with a string and an integer as argument. The issue is that I'm trying to calculate the integer value in an overridden method in the same class. Like so:
super(name, getBaseValue());
This doesn't work because I can't reference the method within the supertype constructor. Maybe I have simply misunderstood the assignment and the UML-diagram. Any ideas how to go about solving this?
getBaseValue() must be static and also use this.getBaseValue (), so that it looks like this:
super(name, this.getBaseValue());
You probably shouldn't do that at all. At the time the constructor runs, the object is not yet created (it's still in the process of being created), and calling a method on it is risky because that method may assume the object is fully created. Even worse, a derived class could also define that method, and then you the parent constructor isn't even done when a child class' method is already called --- chaos.
You can call static methods (which don't require an object instance being created), or you can hard-code any values you want to pass.
See also MET05-J. Ensure that constructors do not call overridable methods in the Secure Java Coding Standard and Sonar Source's warning about this.

What happens if i don't call optional super methods or constructors in extended classes?

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.)

Doing some logic before calling the super constructor in Java

I know that in a derived Java class one may call the super constructor as the first command in the child's constructor. Python for example kindly allows in this case to do some custom logic before calling the super constructor.
My question is: In Java is there any way to achieve this, calling some commands before calling the super constructor? If not, what is the "Java way" of doing this in general?
Example use case: I am writing a game, and in the child class constructor I need to load some assets (only for that child class, not statically), and pass them to the parent constructor.
You can call static methods within the call to super() (e.g. super(initSomething()); if that method is static).
However if your logic is too complicated it might be best to use a static factory method which can then do a little bit more custom initialization before calling into a (private) constructor.
Invocation of a superclass constructor must be the first line in the subclass constructor.
Taken from here. So, no you cannot perform logic before you call the super class's constructor in the way you asked.

How to call a base class method without changing all derived classes

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.

Does exists sense to call method of super?

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.

Categories