How to Call One Constructor from Another in Java

How do I call one constructor from another in Java?

Yes, it is possible:

public class Foo {
private int x;

public Foo() {
this(1);
}

public Foo(int x) {
this.x = x;
}
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

call one constructor from another in java

You can, and the syntax I know is

this(< argument list >);

You can also call a super class' constructor through

super(< argument list >);

Both such calls can only be done as the first statement in the constructor (so you can only call one other constructor, and before anything else is done).

Java calling constructor within another

Your linked example is really long and I'm getting confused by all the non-English comments, so I'll just give you a short example. If you want to call another constructor within a constructor, you just use the this keyword. Here's a sample class that uses this to delegate the work of the "default" (no-arg) constructor to a 1-arg constructor:

public class MyClass {

public final int X;

public MyClass() {
this(1); // Use X=1 by default
}

public MyClass(int x) {
X = x;
}

}

This technique is covered in Using the this Keyword: Using this with a Constructor in Oracle's Java Tutorials.

Why are you allowed to call one constructor from another?

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.

How do I call one constructor from another in JavaScript?

JavaScript doesn’t support overloading of any kind, because function signatures and function calls don’t have to match. On the other hand, function signatures and function calls don’t have to match:

class A {  constructor(a, b) {    if (b === undefined) {      ({a, b} = a);    }
console.log(a + b); }}
new A(1, 2);new A({a: 3, b: 4});

Java: Call constructor from another after if statement

Create some kind of factory:

public class SomeClass
{
// This is the original constructor
public SomeClass()
{
// Do some process
}

// New constructor expecting num > 0
private SomeClass(int num)
{
// Do whatever you want
}

public static SomeClass getIt(int num) throws Exception
{
if (num < 0)
throw new Exception("...");
else if (num > 0)
return (new SomeClass(num));
else
return (new SomeClass());
}

} // SomeClass

How to call an empty constructor from another?

In general, it isn't great practice to call code which could throw in a constructor, and worse then suppress the exception from the caller altogether. However, what you could do is refactor your code so that you move the 'default' initialization of the parameterless constructor into a helper method, which you can then call from your exception handler in the second constructor:

public class Foo {
private int x;

public Foo() {
doDefaultInitialize();
}

public Foo(int x) {
try {
// dodgy code which could throw
}
catch(Exception ge){
doDefaultInitialize();
}
}

private void doDefaultInitialize() {
// Fallback initialization goes here
x = 42;
}
}

Call one constructor from another

Like this:

public Sample(string str) : this(int.Parse(str)) { }


Related Topics



Leave a reply



Submit