What's wrong with using super() in a constructor in Java? - java

When I run static analysis on the following code:
public ExtractDBScripts(String resBundleName)
{
super();
m_mainBundle = ResourceBundle.getBundle(resBundleName);
}
I get the following error:
"JAVA 0058 Constructor 'ExtractDBScripts' calls super()".
What is wrong with calling super() from a constructor?

Probably just that it's completely unnecessary--that is java's default behavior (it will call super for you). You want to use the explicit call to super() if you need to pass a parameter to a non-default constructor.
A static analysis tool will often point out code that does absolutely nothing or is unnecessary to help you reduce clutter. It will also point out a=a; there is nothing wrong with saying a=a; but it's not actually doing anything.

Absolutely nothing wrong with it - although it is implicitly there as the first line of a constructor if you don't declare it yourself (i.e. there's no need to declare it)

I presume the tool you are using is objecting to that line of code because it is not required - if you remove it the compiler will automatically insert it.
See the "Subclass Constructors" section here.

There is nothing wrong with calling super() within a constructor so long as it is the first line in your constructor, so long as you are actually extending a class that has a non private constructor.
If the class you are extending has only one constructor, and it's private then you can't call super().

I would suggest calling super() in your code on purpose, so that it is obvious to other coders what you want to do. It is part of the programming practices where I work and seems to make sense. There may be a way for you to set up the static analysis tool to ignore calls to super() also depending on the software. IntelliJ has annotations for ignoring specific things when it does static analysis.

Related

Calling an abstract method from an interface without overriding it

I am working on a Java project and want to understand the source code before implementing mine into it. The problem im facing is, how can the source code uses the abstract method from an interface without actually overriding it?
At first, I came to this statement:
DeviceService deviceService = context.deviceService();
It is using 'context' to call the method deviceService(). Then, I went up to see where was 'context' being initialized. Then I found this:
private final LinkDiscoveryContext context;
So, 'context' is a type of LinkDiscoveryContext. But then, 'LinkDiscoveryContext' is actually an interface. and the deviceService() is actually an abstract method without having any concrete definition of how the method should do.
I thought we cannot call the method of an interface unless we override it, but why is it working? I may be lack in developer knowledge in Java, and might have provided not enough information. But if the community has any guessing that could result in this working, please share with me.
Thanks in advance.
The class you mention has the constructor that takes instance of LinkDiscoveryContext as argument. So basically you assign a specific implementation to that field using class constructor.
Look for constructor usages to check where it is called from. Hence you will know from which place(s) does that implementation come.

Eclipse: Programmatically manipulate class

I just came across the issue that I had 10 (or so) Java classes for all of which I wanted to:
Add a formal parameter "String newparam" to their constructor
Add this as an actual parameter to the super() call to the super class constructor (thus, the result should be super(..., newparam)).
The reason is, obviously, that the common super class of those classes now has one constructor parameter more and all extending classes had to adapt.
I just can't believe that I need to do this by hand for all classes. Eclipse must have all required concepts like "constructor", "parameter" etc. in its internals. Any way to create a script for this?
I apologize if this is trivial/well known, I have to confess that I really don't know and appreciate any hints.
Changing the constructor signature of every subclass might have to be done with some kind of script. I don't think an IDE would infer the new parameter automatically in each constructor since each subclass could potentially use the new parameter differently.
Since you're using Eclipse, you can at somewhat skip your second requirement by selecting your superclass's constructor and hitting alt+shift+c (shortcut for refactor -> Change method signature...).
When you add the parameter via the GUI provided, all references to that constructor (such as the super calls in the extending classes) will be updated as well. You can even define a default value if you want.
Then if desired you can modify each extending class's constructor to also include the new parameter (by hand, sadly).
Thank you for comments and answers. It currently seems that there is no (widely) known Eclipse-built-in approach to do what I want.
Which is, in short:
Add a new constructor parameter to the super class and, at the same time,
create
the same parameter in the constructors of all extending classes and pass this
parameter through to the super class constructor
It should be noted, however, that the function
Add a new constructor parameter to the super class and add a default value for this parameter to all extending classes
Does work via refactor -> Change method signature... (thanks #Zircon).
A rather obvious solution in case you really have a lot of classes would be to write a script. A Java class was proposed by brahimfes which would have the advantage of not requiring a new language or a new working environment since my question is Java-specific. I also think that maybe a sed script could do the trick. I did, however, not try to, first, recognize the correct lines (constructor and super class constructor call, even though the second one is trivial) and, second, identify the correct position to add the parameters and, third, actually add them. Might work, I didn't try, I just have doubts about how long you would work on such a script until it works with no errors.
Now the solution I finally went for.
I realized that I always have the same key strokes (after I added the new parameter manually to the superclass constructor) in each subclass:
Select the constructor line.
Put the cursor at the and and backtrack 3 positions (parenthesis).
Add the formal parameter.
Go down one line.
Go to the end of this line (which always happens to be the super() call) and backtrack one position.
Add the actual parameter.
There are programs out there allowing to create makros of this kind, I got a trial version of one of them (I'm on a Mac) and did it this way.
Of course, this is still not actually a solution to my question and thus I won't mark this post as a solution. While I now have a makro that that relieves me of almost all typing, I still have to open each class in the editor manually, click the correct line and then fire the makro.
This program will still save me time in the future for similar requirements. But it is not what I hoped it to be, which would be some Eclipse-built-in scripting language with access to Java syntax elements for a more high-level access then regular expressions can offer.

invoking super() when it is doing nothing [duplicate]

This question already has answers here:
Why should I call super() in Java?
(5 answers)
Closed 8 years ago.
What's the point in invoking super()-- the constructor of the super class from within a constructor when the super constructor is doing nothing?
Java APIs are doing it-- saw ArrayList for one,
invoking AbstractList's constructor in its own.
protected AbstractList() { }
is the only constructor of AbstractList.
without the super() call, it'll run anyway-- and with have the same effect.
TIA.
With the default superclass constructor, it's simply a matter of style. If you have no call to another constructor at the start of your constructor (either super(...) or this(...)), then the compiler automatically inserts a call to super(). (The only class that's exempt from this rule is java.lang.Object.)
I don't think there is a point. I've seen some IDEs auto-generate code that uses an explicit call to super() when it's not needed. I wish they wouldn't. It's a coding style I don't care for.
Your subclass will call superclass even if you will not call super() in constructor of subclass.
First of all, the call to super constructor is always made, unless you call another constructor with this(). If you don't type super() at beginning of your constructor, the compiler will type it there for you. (I mean it will compile the file as if you would type it there)
Moreover, if you ask why is the super constructor called at all if it does nothing, it is because (one of the reasons) the super class can change and the constructor can do something in the newer version, and without recompiling the subclass, you already call the super constructor.
I don't think there's any practical reason to use it, per se, because you are correct - it gets called automatically if no super() constructor call is made explicitly.
However, I'll play devil's advocate here and say that I like calls to super() simply because it's more clear with respect to how initialization is actually happening. I've found this to be especially true when you have newer Java developers who might be taking over that particular piece of the code after you get done with it - inexperienced developers down the road will be less prone to making incorrect assumptions about how things actually get initialized, and that's usually worth the minor cost of being overly specific.

Past Java exam about constructors

I am going through a past Java exam and I have a question that I'm stuck on.
The question is: "Any constructor either explicitly or automatically calls the constructor of its parent class, which calls its parent, and so on up the class hierarchy. What is the name of this process?
Thanks for your answers!
It's called "constructor chaining"
#Edit: adding source: Oracle's documentation. Courtsey of Oli Charlesworth.
If a subclass constructor invokes a constructor of its superclass,
either explicitly or implicitly, you might think that there will be a
whole chain of constructors called, all the way back to the
constructor of Object. In fact, this is the case. It is called
constructor chaining, and you need to be aware of it when there is a
long line of class descent.

Overridable method call in constructor

I have a class U and in the constuctor of the class I call overridable method which is public.
NetBeans warns me: Overridable method call in constructor
However, I don't override the method in my project, since class U has no subclasses..
Is it OK to leave it like this? ....calling overridable method in the constructor in this case?
It is not an error. You can ignore it.
If you want to make the compiler happy, make either method, or the whole class final.
As already mentioned you can 'ignore' the warning.
However you do so at your own risk as bugs can creep in at a later date. The reason for the warning is that the compiler cannot prove that a reference to 'this' will not escape the constructor. Which can lead to bugs, as the object being created has not been fully constructed yet and thus the object can be in an invalid state.
It is a warning, not an error, so you can just leave it like this. If you would publish this code however, someone could extend your class U, override the method and get into a lot of trouble.

Categories

Resources