Question

At somewhere, that I can not remember, I read about an alternative way to instatiate a object:

Generally, we instantiate (and assign) this way:

User userObj = new User();
userObj.setId(1);
userObj.setName("Foo");

An alternative way could be:

User userObj = new User()
{{
    setId(1);
    setName("Foo");
}}

I was using this alternative, and it works.

1) Anyone knows what is it? Where is Java documentation link that metion about it?

I stop to use this because I was having problems with interfaces that ClassName implements, but the alternative way don't implements. Oo

public class User implements Serializable
{
    private int id;
    private String name;
    //public Getters and Setters
}

2) When I try to serialize and use it (passing from one activity to another, using: putExtra(String, Serializable) it will throw NotSerializableException. Why?

Edit 1: An anonnymous class also implements the parent 'implementations', like Serializable from ClassName?

Was it helpful?

Solution

You are using anonymous class with initialization block. So it's just an equivalent to the:

SubClass extends ClassName{
   {
      classObj.setParam1(1);
      classObj.setParam2(1);
   }

}

new SubClass();

There is nothing wrong with this construction - but please notice that you are not creating object of ClassName class, but object of SubClass class.

As I said you are using anonymous class (class without name). This is bad - cause while serialization / deserialization JVM should exactly know what is the class of serialization data, so basically - don't use anonymous classes if you want to serialize them.

OTHER TIPS

Ad 1.: This construct ist called "anonymous class".

Ad 2.: I bet your class contains a field which is not Serializable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top