1.

In how many ways an object can be created in Java?

Answer»

There are several ways we can create an object in JAVA

1. A new object can be created using the new operator on the class calling ONE of 

its constructors. MyClass o = new MyClass(); 

2. We can create an object using the Java reflection API - Class.newInstance() if the class has a default constructor. If the class has multiple constructors that take parameters, we can get the corresponding constructor using Class.getConstructor() method and invoke that to create a new object. MyClass o = MyClass.class.newInstance(); MyClass o = MyClass.class 

.getConstructor(int.class) .newInstance(10);  

3. We can invoke clone method on an object to create a duplicate object. 

MyClass o = new MyClass(); MyClass b = (MyClass)o.clone(); 

4. If a state of that object is AVAILABLE in a serialized form, we can DESERIALIZE it to 

create a new object having the same state. ObjectInputStream is = new ObjectInputStream(anIStream); MyClass o = (MyClass) is.readObject(); 



Discussion

No Comment Found