Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
Depends exactly what you mean by create but some other ones are:
When in doubt, look at the language spec.
12.5 Creation of New Class Instances http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5
15.9 Class Instance Creation Expressions http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#41147
Within the Java language, the only way to create an object is by calling it's constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.
From an API user perspective, another alternative to constructors are static factory methods (like BigInteger.valueOf()), though for the API author (and technically "for real") the objects are still created using a constructor.
there is also ClassLoader.loadClass(string) but this is not often used.
and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.
From Josh block: used named static methods as "constructors" as they are more readable, as opposed to many constructors named the same with differing parameter lists.
--James
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:
MyObject object = new MyObject();2. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); 3. Using clone() The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); MyObject object = anotherObject.clone();4. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject();Now you know how to create an object. But its advised to create objects only when it is necessary to do so.
There r Six Ways to Create an Object....... 1) new Class Constructor(); 2) Factory Methods 3) Cloning 4) Using Class methods 5) class.new Instance(); 6) deserilization