Constructor calling itself - java

I have recently found out that no argument constructor and multiple argument constructor cannnot call each other in turns. What is the underlying reason of this limitation? Some might say that constructors are where resources are initialised. So they must not be called recursively. I want to know if this is the only reason or not. Functions/methods/procedures can be called recursively. Why not constructors?

The answer lies in the fact that the call to another constructor is the first line of any constructor and hence your if condition to break out of recursion will never be executed and hence stack overflow.

The main purpose of the constructor is to initialize all the global variables described in a particular class.
For Example:
public class Addition(){
int value1;
int value2;
public Addition(){ // default constructor
a=10;
b=10;
}
public Addition(int a, int b){
this(); // constructors having parameters , overloaded constructor
value1=a;
value2=b;
}
}
public class Main(){
public static void main(){
Addition addition = new Addition(); //or
Addition addition = new Addition(15,15);
}
}
Here, if you want to make instance of the class you can either make instance by calling default constructor or by calling constructor having parameters. So the constructors are overloaded and not overridden. If you want to call another constructor, that can only be done be putting either this() or super() in the first line of the constructor. But this is not prefferable.

Constructors are not intended to be called explicitly outside object initialization, because it's restricted in most (I guess all) languages. Instead, you can create an additional protected Init(...) member function and call it inside the constructor.

Your statement that constructor cannot call other constructors are not true for every programming languages. At least I know Java can do this, while C++ cannot. But you could easily overcome this limitation by writing a private __init function and let all your constructors call it.

In all languages you've listed objects contain finite (and normally short) set of properties. Each property could contain recursive structure (i.e. list), but it still represented by a single property in the object.
I don't see need to recursively call constructors. It feels like a strange use recursion to initialize several well know properties.
As you've said you can call constructors in non-recursive way to share code in some languages you've mentioned.
C#: Using Constructors
public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}

Related

Advantages/disadvantages of init method

What are the advantages/disadvantages of init method over a constructor in java? They both have the same purpose. How to choose between them?
public class A {
private int x;
public A(int x){
this.x = x;
}
public void init(int x){
this.x = x;
}
}
Here we can use either constructor or init method.
You are wrong. They do not have the same purpose.
A constructor is always required when you want to create a new object using the new() operator.
A init method is something that might make sense in certain contexts, for example servlet stuff (see here for further reading regarding this aspect).
And please note: in your example, one could your init method more as a setter - as it is simply setting the corresponding field.
Coming from there:
first of all, you think about the constructors that you want to put into you class (by asking: which information is required to create a new instance of the class)
if there is special need, then consider adding setters for specific fields - or as layed out above, it might be required to provide an init() method (in case where object creation and initializiation can not happen at the same point of time)
Constructor is not a regular method. It's special in a sense that it gets always called when you invoke new A(). If you don't provide a constructor, Java creates one automatically. As a consequence, constructors do not have a return (i.e. they return this) and always have the same name as the class.
On the other hand, init is a regular method, which you can call - or not. There is no universally accepted consensus for any kind of "init" methods. So it depends on what you want to do. If you want to ensure that the new calls your logic, use constructor. If you want to have your own stuff, use plain methods. You can mix and match, just be sure to write a good documentation about how your class is supposed to be used.

Why are you allowed to call one constructor from another?

I was looking at other questions on SO, but I didn't really see an explanation for my question. I read that calling a constructor from another constructor (using the this keyword) was valid, but I didn't understand why it was valid.
Previously, I thought that only one constructor could act per object. Constructor chaining seems to break this logic, in that while calling one constructor, it runs another in conjunction to the original, targeted constructor. Why does constructor chaining work?
We chain (call) one constructor from other within the same class so that we can avoid code duplication. Without chaining every constructor, we end up repeating business details and that leads to code duplication and hard to maintain the code as well.
Imagine you are creating a Bus.
public class Bus {
int noOfSeats;
String busColor;
public Bus() {
this(40); //// Using another constructor and proceeding with default values..
}
public Bus(int seats) {
this(seats,"red"); // Using another constructor and proceeding..
}
public Bus(int seats, String color) {
this.noOfSeats = seats;
this.busColor = color;
}
}
And the person using this class can use only constructor at a time, where as you are using chaining internally. Imagine that you have a method which initializes things with default values and calling it in the constructor. There's nothing wrong in that, right?
Just to clarify, the person who is creating the object is calling only one constructor. The invoked constructor calls others which is internal to that class.
Delegated constructors reduce the amount of duplicate code, since you can exploit the functionality set up in one constructor by calling it from another one.
Until this feature was designed into languages, we had to rely on "initialisation"-type functions that were called from constructors. That was a pain for two reasons (i) you could never guarantee that the functions were only called from constructors, and (ii) calling class methods from constructors is always a design "smell".
It allows to clarify the logic and reduce the code.
Is nesting constructors (or factory methods) good, or should each do all init work
It's reasonable to chain constructors together, the version with fewer parameters calls the version with more parameters. It makes very clear what's happening, and all the real "logic" (beyond the default values) is in a single place. For example:
public class Foo {
private static final int DEFAULT_X =10;
private static final int DEFAULT_Y =20;
private int x;
private int y;
private int precomputedValue;
public Foo(int x, int y) {
this.x = x;
this.y = y;
precomputedValue = x * y;
}
public Foo(int x) {
this(x, DEFAULT_Y);
}
public Foo() {
this(DEFAULT_X, DEFAULT_Y)
}
}
Not a Java dev here, but in Python this is also allowed and pretty much normal.
Whenever you inherit a class, you might want to call the parent class's constructor prior adding your own stuff-and-recipes.
This allows you to benefit the parent class's construction features. Whenever you do not know exactly what the parent class does you most of the time always call it first in order to avoid the parent's class features and methods being broken.
The fact that the confusion originates from every instance should call one ctor is absolutely right. The constructor chained another is used to avoid code duplication and simplicity because copying same code is really overhead. Sometimes maybe we need two constructors, first one just takes two parameters the other one takes three parameters. But, three parameters-ctor uses same variables of two parameters-ctor. Do you prefer copy-paste same assignmets or merely call the other ctor by this?
As a supplement to the other answers, I would like to share another use for calling a constructor from a constructor that I use often.
Another strategy of constructor chaining that I find useful is providing default implementations / auto-injection for Interfaces.
public class Foo {
private readonly ILogger _logger;
//Default implementation for most cases
public Foo() : this(new DefaultLoggerImplementation()) {}
//DI Constructor that allows for different implementations of ILogger
//(Or Mocks in testing)
public Foo(ILogger logger)
{
_logger = logger;
}
public void Log(string message)
{
_logger.log(message);
}
}
This way if you have a default implementation for an interface it is auto injected via new Foo()
If you have a case with different ILogger behavior it is easily injectable, this also promotes the ability to Mock the interface in your unit testing framework.

Java - Is it possible to write public void() in Constructor?

I couldn't find information if it is possible to write public void in constructor section. Is it possible?
At the byte code level, a constructor is always void so it would be redundant to specify it. i.e. the constructor is always called <init>V i.e. the V is the return type where V == void. Similarly the static initialiser is <clinit>V You will see this notation if you take a stack trace (e.g. print an exception) while in these methods.
The constructor actually takes the object to be initialised as an argument as the object is created before calling the constructor. Note: you can create the object without calling a constructor with Unsafe.allocateInstance(Class)
I couldn't find information if it is possible to write public void in constructor section. Is it possible?
It is not possible to write it as Java distinguishes a constructor from a method is that it must have the same name as the class, and it must not specify a return type. If you specify a return type, it assumes it's a method.
The notation x = new Clazz() also limits the number of return values to 1 which is the object. There is no easy way to modify this notation to return more than one object. i.e. supporting a return type for constructors would not be easy.
If you want to define a return type, most likely you are thinking of a factor method like this.
public static MyInterface createObject() {
return new MyClass();
}
Note how the return type is different to the class actually created, but there is still only one reference returned.
The constructor syntax is defined in the Java Language Specification. Anything else is incorrect.
The question is unclear. Peter Lawrey answered one interpretation, this is an answer to another.
You cannot declare methods within a constructor. You can, however, declare a class and declare variables.
Because you are able to declare a class within a constructor, you could declare a method inside of a class and then use the class. If the method isn't static you can construct an object of the class.
No, Java only allows a method to be declared within a class, not within another method or constructor.Indirectly you can do something like this :
public A() {
class B {
public void m() {
}
}
}

Can you call two different overloaded constructors from in the same instance of a class in java?

I am working on a simple calculator problem and i am making a class specifically to handle the operations. I am making two constructors within the class one taking one int and one taking two. What i plan to do is that when the user inputs the first number into the program, the first constructor will be called and the first number will be saved. When they enter the second number, the same instance of the class will be called but this time with both the variables in a constructor. Is this possible? Is there an easier way to do this? thanks.
You can't initialize the same instance of a class multiple times. What you can do, however, is change the value of any non-final instance or static variables in the class after you've called the constructor. It's best coding practice to avoid adding any code except for initialization of instance variables to the constructors, and what you can do is move any code in question to other methods so you can call it where you were thinking of calling the constructor the 2nd time.
No, this is not directly possible since a constructor can only be called upon class instantiation. You can use something like the builder pattern instead.
You can call another constructor within another overloaded constructor.
In your constructor, type this(yourParameters) and that calls the other constructor.
Example:
class Example
{
public Example()
{
this(1); // calls the other constructor
}
public Example(int par1)
{
// some code here
}
}
But other than that, you cannot call constructors explicitly like you can with methods.

Why must delegation to a different constructor happen first in a Java constructor?

In a constructor in Java, if you want to call another constructor (or a super constructor), it has to be the first line in the constructor. I assume this is because you shouldn't be allowed to modify any instance variables before the other constructor runs. But why can't you have statements before the constructor delegation, in order to compute the complex value to the other function? I can't think of any good reason, and I have hit some real cases where I have written some ugly code to get around this limitation.
So I'm just wondering:
Is there a good reason for this limitation?
Are there any plans to allow this in future Java releases? (Or has Sun definitively said this is not going to happen?)
For an example of what I'm talking about, consider some code I wrote which I gave in this StackOverflow answer. In that code, I have a BigFraction class, which has a BigInteger numerator and a BigInteger denominator. The "canonical" constructor is the BigFraction(BigInteger numerator, BigInteger denominator) form. For all the other constructors, I just convert the input parameters to BigIntegers, and call the "canonical" constructor, because I don't want to duplicate all the work.
In some cases this is easy; for example, the constructor that takes two longs is trivial:
public BigFraction(long numerator, long denominator)
{
this(BigInteger.valueOf(numerator), BigInteger.valueOf(denominator));
}
But in other cases, it is more difficult. Consider the constructor which takes a BigDecimal:
public BigFraction(BigDecimal d)
{
this(d.scale() < 0 ? d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale())) : d.unscaledValue(),
d.scale() < 0 ? BigInteger.ONE : BigInteger.TEN.pow(d.scale()));
}
I find this pretty ugly, but it helps me avoid duplicating code. The following is what I'd like to do, but it is illegal in Java:
public BigFraction(BigDecimal d)
{
BigInteger numerator = null;
BigInteger denominator = null;
if(d.scale() < 0)
{
numerator = d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
denominator = BigInteger.ONE;
}
else
{
numerator = d.unscaledValue();
denominator = BigInteger.TEN.pow(d.scale());
}
this(numerator, denominator);
}
Update
There have been good answers, but thus far, no answers have been provided that I'm completely satisfied with, but I don't care enough to start a bounty, so I'm answering my own question (mainly to get rid of that annoying "have you considered marking an accepted answer" message).
Workarounds that have been suggested are:
Static factory.
I've used the class in a lot of places, so that code would break if I suddenly got rid of the public constructors and went with valueOf() functions.
It feels like a workaround to a limitation. I wouldn't get any other benefits of a factory because this cannot be subclassed and because common values are not being cached/interned.
Private static "constructor helper" methods.
This leads to lots of code bloat.
The code gets ugly because in some cases I really need to compute both numerator and denominator at the same time, and I can't return multiple values unless I return a BigInteger[] or some kind of private inner class.
The main argument against this functionality is that the compiler would have to check that you didn't use any instance variables or methods before calling the superconstructor, because the object would be in an invalid state. I agree, but I think this would be an easier check than the one which makes sure all final instance variables are always initialized in every constructor, no matter what path through the code is taken. The other argument is that you simply can't execute code beforehand, but this is clearly false because the code to compute the parameters to the superconstructor is getting executed somewhere, so it must be allowed at a bytecode level.
Now, what I'd like to see, is some good reason why the compiler couldn't let me take this code:
public MyClass(String s) {
this(Integer.parseInt(s));
}
public MyClass(int i) {
this.i = i;
}
And rewrite it like this (the bytecode would be basically identical, I'd think):
public MyClass(String s) {
int tmp = Integer.parseInt(s);
this(tmp);
}
public MyClass(int i) {
this.i = i;
}
The only real difference I see between those two examples is that the "tmp" variable's scope allows it to be accessed after calling this(tmp) in the second example. So maybe a special syntax (similar to static{} blocks for class initialization) would need to be introduced:
public MyClass(String s) {
//"init{}" is a hypothetical syntax where there is no access to instance
//variables/methods, and which must end with a call to another constructor
//(using either "this(...)" or "super(...)")
init {
int tmp = Integer.parseInt(s);
this(tmp);
}
}
public MyClass(int i) {
this.i = i;
}
I think several of the answers here are wrong because they assume encapsulation is somehow broken when calling super() after invoking some code. The fact is that the super can actually break encapsulation itself, because Java allows overriding methods in the constructor.
Consider these classes:
class A {
protected int i;
public void print() { System.out.println("Hello"); }
public A() { i = 13; print(); }
}
class B extends A {
private String msg;
public void print() { System.out.println(msg); }
public B(String msg) { super(); this.msg = msg; }
}
If you do
new B("Wubba lubba dub dub");
the message printed out is "null". That's because the constructor from A is accessing the uninitialized field from B. So frankly it seems that if someone wanted to do this:
class C extends A {
public C() {
System.out.println(i); // i not yet initialized
super();
}
}
Then that's just as much their problem as if they make class B above. In both cases the programmer has to know how the variables are accessed during construction. And given that you can call super() or this() with all kinds of expressions in the parameter list, it seems like an artificial restriction that you can't compute any expressions before calling the other constructor. Not to mention that the restriction applies to both super() and this() when presumably you know how to not break your own encapsulation when calling this().
My verdict: This feature is a bug in the compiler, perhaps originally motivated by a good reason, but in its current form it is an artifical limitation with no purpose.
I find this pretty ugly, but it helps
me avoid duplicating code. The
following is what I'd like to do, but
it is illegal in Java ...
You could also work around this limitation by using a static factory method that returns a new object:
public static BigFraction valueOf(BigDecimal d)
{
// computate numerator and denominator from d
return new BigFraction(numerator, denominator);
}
Alternatively, you could cheat by calling a private static method to do the computations for your constructor:
public BigFraction(BigDecimal d)
{
this(computeNumerator(d), computeDenominator(d));
}
private static BigInteger computeNumerator(BigDecimal d) { ... }
private static BigInteger computeDenominator(BigDecimal d) { ... }
The constructors must be called in order, from the root parent class to the most derived class. You can't execute any code beforehand in the derived constructor because before the parent constructor is called, the stack frame for the derived constructor hasn't even been allocated yet, because the derived constructor hasn't started executing. Admittedly, the syntax for Java doesn't make this fact clear.
Edit: To summarize, when a derived class constructor is "executing" before the this() call, the following points apply.
Member variables can't be touched, because they are invalid before base
classes are constructed.
Arguments are read-only, because the stack frame has not been allocated.
Local variables cannot be accessed, because the stack frame has not been allocated.
You can gain access to arguments and local variables if you allocated the constructors' stack frames in reverse order, from derived classes to base classes, but this would require all frames to be active at the same time, wasting memory for every object construction to allow for the rare case of code that wants to touch local variables before base classes are constructed.
"My guess is that, until a constructor has been called for every level of the heierarchy, the object is in an invalid state. It is unsafe for the JVM to run anything on it until it has been completely constructed."
Actually, it is possible to construct objects in Java without calling every constructor in the hierarchy, although not with the new keyword.
For example, when Java's serialization constructs an object during deserialization, it calls the constructor of the first non-serializable class in the hierarchy. So when java.util.HashMap is deserialized, first a java.util.HashMap instance is allocated and then the constructor of its first non-serializable superclass java.util.AbstractMap is called (which in turn calls java.lang.Object's constructor).
You can also use the Objenesis library to instantiate objects without calling the constructor.
Or if you are so inclined, you can generate the bytecode yourself (with ASM or similar). At the bytecode level, new Foo() compiles to two instructions:
NEW Foo
INVOKESPECIAL Foo.<init> ()V
If you want to avoid calling the constructor of Foo, you can change the second command, for example:
NEW Foo
INVOKESPECIAL java/lang/Object.<init> ()V
But even then, the constructor of Foo must contain a call to its superclass. Otherwise the JVM's class loader will throw an exception when loading the class, complaining that there is no call to super().
Allowing code to not call the super constructor first breaks encapsulation - the idea that you can write code and be able to prove that no matter what someone else does - extend it, invoke it, instansiate it - it will always be in a valid state.
IOW: it's not a JVM requirement as such, but a Comp Sci requirement. And an important one.
To solve your problem, incidentally, you make use of private static methods - they don't depend on any instance:
public BigFraction(BigDecimal d)
{
this(appropriateInitializationNumeratorFor(d),
appropriateInitializationDenominatorFor(d));
}
private static appropriateInitializationNumeratorFor(BigDecimal d)
{
if(d.scale() < 0)
{
return d.unscaledValue().multiply(BigInteger.TEN.pow(-d.scale()));
}
else
{
return d.unscaledValue();
}
}
If you don't like having separate methods (a lot of common logic you only want to execute once, for instance), have one method that returns a private little static inner class which is used to invoke a private constructor.
My guess is that, until a constructor has been called for every level of the heierarchy, the object is in an invalid state. It is unsafe for the JVM to run anything on it until it has been completely constructed.
Well, the problem is java cannot detect what 'statements' you are going to put before the super call. For example, you could refer to member variables which are not yet initialized. So I don't think java will ever support this.
Now, there are many ways to work around this problem such as by using factory or template methods.
Look it this way.
Let's say that an object is composed of 10 parts.
1,2,3,4,5,6,7,8,9,10
Ok?
From 1 to 9 are in the super class, part #10 is your addition.
Simple cannot add the 10th part until the previous 9 are completed.
That's it.
If from 1-6 are from another super class that fine, the thing is one single object is created in a specific sequence, that's the way is was designed.
Of course real reason is far more complex than this, but I think this would pretty much answers the question.
As for the alternatives, I think there are plenty already posted here.

Categories

Resources