1
class Formulas{
    private double x=0, y=0, z=0, t=0, theta=0, v=0, a=0;
}

Assume I have a class similar to the one above and want to overload the constructor for all possible combinations of the given fields. Is there a faster way to generate all necessary constructors using Eclipse?

Nate
  • 16,748
  • 5
  • 45
  • 59
A.G
  • 11
  • 2

3 Answers3

6

Consider two possible constructors:

public Formulas(double x); public Formulas(double theta);

They have the same signature so ultimately the compiler can't tell them apart, so this is illegal.

The short answer is it can't be done. Consider a Builder or a Factory pattern instead.

You could also "divide and conquer" the arguments. I'm not sure what your v and a are, but, if they were angular values associated with theta, you could use a Point3D and an Angle3D class to hold the 6 inputs, and have a constructor

public Formulas(Point3D point, Angle3D angle)

user949300
  • 15,364
  • 7
  • 35
  • 66
5

Much cleaner and more readable, the Builder Pattern.

As for "a fast way", check out Automatically create builder for class in Eclipse.

public class Formulas {
    private double x=0, y=0, z=0, t=0, theta=0, v=0, a=0;

    public Formulas() {

    }

    public Formulas withX(double x) {
        this.x = x;
        return this;
    }

    public Formulas withY(double y) {
        this.y = y;
        return this;
    }

    // repeat

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    // repeat...

}

Usage

public static void main(String[] args) {
    Formulas f = new Formulas().withX(2).withY(4);
    System.out.printf("%s %s\n", f.getX(), f.getY()); // 2.0 4.0
}
Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
1

Eclipse has a tool to generate a constructor using fields but not to generate all possible combinations of constructors.

To generate a constructor using some or all available fields, go to Source > Generate Constructor using Fields and select the fields you want. then click OK and the constructor is automatically generated.

Note: Two constructors with the same parameter type with different variable names are not accepted in Java. For instance:

Constructor(Object parameterOne){ ... }
Constructor(Object parameterTwo){ ... } 

Will not compile.

fill͡pant͡
  • 1,147
  • 2
  • 12
  • 24