1

While learning Java's basics, I remember coming across a particular syntax for passing arguments to a class constructor. I found this syntax extra read-able, but I'm sadly not able to find it anymore. It looked somewhat like the following:

// Creating an instance of the Employee class (has property name, salary, etc)
Employee fred = new Employee({
    name: "Fred",
    salary: 5000
    job: Jobs.PROGRAMMER
});

As you probably can see, it becomes very clear what each argument to the constructor means, which eliminates the need to look at documentation - just to understand simple code.

Am I mixing languages up or does a syntax somewhat like this exists? An eventual link to the manual would be appreciated.

4

3 回答 3

2

You may be thinking of something similar to the following code:

SomeClass foo = new SomeClass(/* args */) {
  {
    protectedOrPublicField = someValue;
    protectedOrPublicMethod(/*args*/);
  }
}

This constructs an object and invokes methods at the same time. It's known as double brace initialization. It's not quite what you were asking for, but its the only syntax I know of in Java that looks anywhere near familiar.

Note that you could use this to set the value of protected or public fields. That would then look rather similar to your example.

If you want your constructors to be more readable, consider using a self-describing static factory method or a builder pattern. See Joshua Bloch's excellent Effective Java 2nd Edition for more details or consult your favourite search engine.

于 2012-09-08T12:07:42.547 回答
2

This is not Java syntax (and never was).

What you can do is to achieve something similar is to use Anonymous classes with initializers like this

class Employee{
    String first;
    String last;
}

Employee mike = new Employee(){{
    first = "Mike";
    last  = "Meyers";
}};

There is an explanation of what is going on here: http://blog.schauderhaft.de/2012/08/19/named-parameters-in-java-another-alternative/

于 2012-09-08T12:13:08.780 回答
0

Yeap, you are mixing a new feature of C# named and optional arguments. However, if you create something like @Duncan Jones said that is quite the same anonymous class. However, according to Java Specification 15.9.1

An anonymous class cannot have an explicitly declared constructor.
于 2012-09-08T12:18:25.340 回答