How to Create Objects in Java?
As per java, a class is nothing but blueprint of an objects, We create an object from a class. 1) Using new Keyword : 2) Using New Instance : Suppose if we know the name of the class & it has a public default constructor we can create an object by Class.forName. Class.forName loads the Class in Java, it doesn’t create any Object. To Create an Object of the Class we have to use the new Instance Method of the Class. 3) Using clone() method: On calling clone() for any object, the JVM creates a new object and copies all content of the previous object into it. Creating an object by the clone method does not invoke any constructor.
We have different ways to create object for class in Java.
Creating Object with new keyword is the common way in java. By using this way we can call any constructor we want to call (no argument or parameterized constructors).
public
class
ObjectWithNew{
String name =
"New Key Word"
;
public
static
void
main(String[] args)
{
// Here we are creating Object of
//
ObjectWithNew using new keyword
ObjectWithNew obj = new
ObjectWithNew();
System.out.println(obj.name);
}
}
public
class
ObjectWithNewInstance
{
String name =
"Object with New Instance"
;
public
static
void
main(String[] args)
{
try
{
Class cls = Class.forName("ObjectWithNewInstance");
ObjectWithNewInstanceobj =
(ObjectWithNewInstance) cls.newInstance();
System.out.println(obj.name);
}
catch
(ClassNotFoundException e)
{
e.printStackTrace();
}
catch
(InstantiationException e)
{
e.printStackTrace();
}
catch
(IllegalAccessException e)
{
e.printStackTrace();
}
}
}
To use clone() method for an object we need to implement Cloneable and define the clone() method in it.
public
class
ObjectWithClone
implements
Cloneable
{
@Override
protected
Object clone()
throws
CloneNotSupportedException
{
return
super
.clone();
}
String name =
"Object with Clone"
;
public
static
void
main(String[] args)
{
ObjectWithClone obj1 = new
ObjectWithClone();
try
{
ObjectWithClone obj2 = (ObjectWithClone ) obj1.clone();
System.out.println(obj2.name);
}
catch
(CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}