java constructor best practice - java

What is the advantage of having constructor simillar to the one mentioned below:-
class A{
public A(A a){}
public A(){}
}

If you mean the one with the parameter, there's no reason for having that at all, given that it completely ignores the parameter, and there's already another constructor with the same effect.
If you can give a more realistic example, we may be able to give more useful information...

A(A a){/*do something*/} Can be helpful as copy constructor.

As others have said, you have a copy constructor. There are a number of reasons why you may want a copy constructor. Some of those are:
You can provide an alternative to the clone method. (Which is implemented via the Clonable interface.)
Copy constructors are easily implemented.
You can use another constructor to build the copy (by extracting data from the original object and forwarding to a regular constructor).
Check out the link I added to this post for more information about copy constructors and why you would want to use them (if you need them).

There is no advantage unless you need to have a copy constructor. I would suggest using the clone() method if this object should be clonable rather than using a copy constructor semantic.

You're question is very unclear, but basically if you hava a class, that has a constructor, that takes an instance of the same class, then you have a copy constructor. i.e. a constructor that creates a new instance with the same internal values as the original.
Edit -- assuming of course that your constructor does something other than just create a new instance.

It could also be useful in a number of delegation-based design patterns such as decorator or proxy etc.
Providing a default constructor might still be considered good practice, especially in scenarios where dependency injection or serialization are considered.

Related

Java Call constructor multiple times

I have a class that's essentially like:
class Child extends Parent {
public void reinitialize() {
super(); // illegal
}
}
Basically, I want to call the constructor again to reinitialize. I can't refactor out the initialization code into its own method, because Parent is a library class I can't modify the source of.
Is there a way to do this?
No, there is no way to do this. Even at the JVM bytecode level, a chain of <init> methods (constructors) can be called at most once on any given object.
The usual answer is to refactor the code out into a normal instance method, but as you said, this is impossible.
The best you can do is to find a way to redesign to get around the need for reinitialization. Alternatively, if there's a specific behavior in the parent constructor you need, you might be able to duplicate it yourself.
The only work around for this is to either
create a new object each time you need to "re-intialise" it.
use delegation instead of inheritance, even if you have to use both. By using delegation you can replace the instance.
create a re-initialise method which does much the same thing as the parent constructor. e.g. replace fields or clear collections, using reflections if you have to.
One way to do this is provide a static method which returns a new Child object. Alternatively, you can simply create a new Child object in the client code. Either way, it sounds like you will be unable to reuse an existing object.
There are several ways to achieve this. One of them is create another method, for example "init". This "init" method should be invoked from either the constructor or the reinitialize method.

Can Result objects be allowed to have behavior?

This is in reference to the ResultObjectPattern.
Usually, the ResultObject will be rather simple with just private instance variables referring to various components of the result, and getter methods (possibly setters too?) for those.
Now, would it be a bad idea to add behavior methods to the ResultObject? For example, let's say the ResultObject pushed out one or more of its instance variables to a cache and retrieve them back only when needed, or provided methods that do some computation,-- would that be okay, or would these be things that'd rather be handled by a separate (singleton/utility) class such as a ResultObjectManager?
I think if behavior is strongly related to data and behavior is not beyond the scope of RO responsibilities - is not bad idea.
I'd say that when the choice is between adding an instance method to a regular class and adding a static method to anything or any method to a singleton, I'll add the instance method to the regular class. It's the OO way.

Setters vs Overloaded constructors in Java

I am not sure if a similar question has been asked before, searched for it, but did not get any helpful answers.
As the question suggests, what is better, having an overloaded constructor or having multiple setter functions?
Scenario:
public class Something {
private int a;
private int b;
public Something(int a, int b) {
this.a = a;
this.b = b;
}
... // Do Something
}
Now, my basic requirement was for to have two parameters only. Now tomorrow, the requirement is changed and I am asked to add a new parameter, c and then the next day d, and given a statement saying we can have more fields.
I already have dependency for this constructor in multiple projects. Now, back to my question
Is it advisable to keep adding the new fields to the already overloaded constructor?
Create a new overloaded constructor every time I need to add a new field so that I don't break dependent code?
Or simply use the default empty default constructor and use setters only (messing up my immutability, which is not of high concern)
What is the advice that you can give me?
The most pleasant way to do this is to continue adding the fields to your constructor -- having setters means you can't have immutable objects, and immutable objects are always nice -- but possibly to investigate the builder pattern, which can help you limit yourself to just one constructor that gets called and "filled in" by the builder object.
The good thing about a constructor, as opposed to setters, is that it allows you to enforce the setting of required properties for an instance, rather than having the object be in a bad state until its correct setters are called. Also, as the other posters mentioned, immutability can be a very good thing, particularly in a multi-threaded context.
Nevertheless, your instincts are correct: constructors can grow unwieldy. To second the other posters yet again, the builder pattern can give you the best of both worlds in this situation. If you don't want the builder to be a nested class of the product, as it is depicted in the Java example in the Wikipedia article, then just put it in the same package as the product, and give the product package-protected setters. Also, you can add logic to enforce the setting of mandatory properties when the caller declares building to be complete.
The objective of having different constructors is to increase the reusability of the class. I think it will be more helpful to have a few different constructors that serve to your needs rather than having a lot of setters.
Also the constructors are more specific and improve the readability of your class and the api.
Do your other projects that depend on 2-arg constructor benefit in any way from new parameters? Do 2-arg constructors make sense with your new requirements?
Maybe you need to create another class, e.g. SomethingEx(Something) which would carry additional fields and have different constructors, but would share useful methods.
If useful methods to share are few and very short, it may be better to create an entirely different class, just to have fewer dependencies.

GetUninitializedObject in Java?

First, the situation. I am doing school project. I have to implement my own clone function. It takes object as argument, creates exact copy and returns it. Function declaration:
Object clone(Object obj);
Problem is that obj.getClass() doesn't have to have appropriate constructor. For example private constructor that takes 3 arguments. So I don't know how should I create objects. Constructor.newInstance(arguments) won't work. And I don't know any other way. So I was wondering if there isn't such method as GetUninitializedObject, which is in C#. Suggestions for different solutions are welcomed.
Thanks in advance
Have a nice day
You can get constructors of a class and also their parameter types. you can read from here:
http://tutorials.jenkov.com/java-reflection/constructors.html
if a class hasn't any public constructors, there's nothing to do with that.
In Java your best options are either to require a public no-args constructor and require setters (often referred to as a Bean), or use Java's built in Serialization via ObjectInputStream and ObjectOutputStream. You can also use Object.clone() to do this, although it's discouraged by many Java experts (for example, Josh Bloch warns against it in "Effective Java")

Object doesn't do anything after instantiation

I have an object that I instantiate - it's quite nifty as it also extends a superclass and does some stuff in the constructor - in fact all the vital parameters and method calls are handled in the constructor.
After this I never call the object again to do something - I don't pass it to any other objects either - after it's instantiated it does it stuff and all is good. Is this the wrong way to do it?
Yes, doing significant work in the constructor is usually a bad idea.
Could you do this through a static method instead? The static method could create an instance of the superclass and then do whatever it needs to. The only problem with this approach would be if the superclass called virtual methods during its constructor, but that's a code smell in itself...
It may be a smell from the superclass, not the subclass.
Why do you need to do that? Is there functionality in the superclass that is publicly accessible only through the constructor? If so then you probably do need to create an instance to access that functionality. But it may be better to hide that behaviour behind a normal method rather than a subclass constructor.
But that's still not as good as fixing the superclass.
There should a purpose for the object to exist. Constructor is only a tool for preparing the object so it can work as needed after creation. If you don't use the object, you don't need to create it either.
Creation of unnecessary objects consumes memory and also makes garbage collector do more work, so you should consider rewriting code (possibly with a static method as it has already been suggested).

Categories

Resources