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.
Related
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.
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 just noticed in the codebase of a very large project I am assigned at work, a particular class has no constructor. Its subclass though, calls super().
Can someone please explain what is going when a subclass calls super(), but there is no constructor in the parent?
(I can guess that the effect is like calling an empty constructor, but I am wondering if there is anything else going on behind the scenes).
If you do not have any parameterized constructor and I strictly mean no constructor then and only then java will add a default constructor(One with no parameters) for you.
Each constructor must call a constructor of it's super class. You cannot perform any other action in the subclass constructor untill all constructors of superclasses up the inheritance tree are called. Hence this call must be the 1st line of your subclass constructor If you do not provide one again java does that for you.
Refer
Why does this() and super() have to be the first statement in a constructor?
If a class doesnt having any constructors means it is gifted with empty constructor by the java compiler.
If you place the empty constructor , then the compiler will not because it is already mentioned by you.
Now If you want your own constructor with your own parameters, Then there will not be any default constructor by the java compiler
Check this for more info on constructors
Subclass constructor always call its parent constructor first before executing any statement. If there is no consturctor in parent class then whether you call it or not explicitly, super() call will be added in the code by java compiler and hence will be executed by JVM.
The java compiler will provide a default no argument constructor without a body when a class doesn't declare any constructors. Calling super() in a base class constructor will invoke that default constructor.
Can someone please explain what is going when a subclass calls
super(), but there is no constructor in the parent?
If parent class doesn't have any constructor then java compiler will call the default constructor of it. If you don't want to call default constructor then you can create your own empty constructor in that class.
Compiler add a default constructor with no parameter into your class if you do not provide it explicitly. So in your case it is calling default constructor.
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
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.