How many ways to create an object for class
Hello Friends,
I am working with JAVA, and i used to create an Object for a class in a traditional way, that just simply, whatever class I create, i create the object in the Void main and through which i access the class.This is the simple the way i create the object but can anyone suggest is there any other way by which i create the class and access them.
Thanks for your suggestions.
Re: How many ways to create an object for class
Hey as per my knowledge
- using new keyword
- class.forName() : provided it has default public constructor called up
- even deserialization creates an object from its serialized form
Re: How many ways to create an object for class
As my concern we can create an object in java by 4 ways.
1.By using new operator
Integer i=new Integer();
2.Using Class
Class myclass=Class.forName(MyClassName);
myclass.newInstance();
3.Using shallow clonig
4.Using DeepCloning i.e Serialization
Re: How many ways to create an object for class
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
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.