Passing arguments to a constructor, alternative syntax

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.

Answers


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/


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.


Need Your Help

Android animate view along a curved path

android animation viewanimator

I'm trying to move my image from one point to another using this answer to achieve my animation. However this animation is not showing. Below is the code I'm using

How to write out sql in php?

php mysql sql

Hello i am trying to get this into a function getTableResults. I am unfamiliar with php.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.