Print Shortlink

Java, C#, Groovy, Ext JS4 and constructors

I have always found writing/generating constructors for a class a very boring task in Java. I wanted a much easier way to initialize member variables instead of writing overloaded constructors.

If you want to write a simple “Employee” class with name and salary variables I had to write this code in Java most of the time.

public class Employee{
private String name;
private double salary;
        //Hate to write this code     
        public Employee(){} //This is for the Java Beans
public Employee(String name,double salary){ = name;
this.salary = salary;
Employee e1 = new Employee (“Sam”,20000);

C# 3.0 came up with the concept of object initializers which removed the need for having constructors.
  public class Employee {
     public String name {get;set;}
     public double salary {get;set;} 
 Employee e1 = new Employee(name:”Sam”,salary:20000);

It was definitely better than Java, but you still had to write those silly {get;set;} block to designate name and salary as properties. Object initializers are available only for properties.

Groovy finally came to my rescue. It injected a lot of code and removed the need for writing code that I had always considered waste of effort and time.
class Employee{
     String name
     double salary
e1 = new Employee(name:”Sam”,salary:20000)

Happiness is always short lived. I have been writing classes in Ext JS4 like this off late.
//Ext JS4
   constructor : function(name,salary){ = name;
        this.salary = salary;  
var e1 = new Com.durasoft.Employee(“Sam”,20000);

Though frameworks like Ext JS 4 have succeeded in making people take JavaScript as a serious OO language, it still has a long way to go in terms of providing concise syntax.

I hope the future releases of Ext JS4 come up with a groovier syntax.

Page 1 of 1

2 Responses

  1. Anonymous
  2. Prabhu Sunderaman

Leave a Reply