Different ways to create an object in Java
1) Using New Keyword
. This is the most common way to create an object in java. Almost 99% of objects are created in this way. It is the most basic way to create an object.
public class CreateObjects {
public static void main(String[] args) {
Create obj = new Create();
}
}
class Create{
String name;
}
2) using
Class.forName()
.
Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java,
not by the programmer writing the class. They are the same for every
class. Calling newInstance() on that gives you an instance of that class. If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyClass object = (MyClass ) Class.forName("com.abc.MyClass ").newInstance();
MyClass object = (MyClass ) Class.forName("com.abc.MyClass ").newInstance();
3. using clone() .
The clone() can be used to create a copy of an existing object.
MyClass objmyclass= new MyClass ();
MyClass object = objmyclass.clone();
4) Deserialization
MyClass objmyclass= new MyClass ();
MyClass object = objmyclass.clone();
4) Deserialization
Using object deserialization .Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream ois = new ObjectInputStream(anInputStream );
MyClass object = (MyClass) ois.readObject();
ObjectInputStream ois = new ObjectInputStream(anInputStream );
MyClass object = (MyClass) ois.readObject();
5) Factory Method
By Using Factory Method:
ClassName ObgRef=ClassName.FactoryMethod();
Example: RunTime rt=Runtime.getRunTime();//Static Factory Method.
ClassName ObgRef=ClassName.FactoryMethod();
Example: RunTime rt=Runtime.getRunTime();//Static Factory Method.
6) JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
Read More
Java 8 FeaturesHow to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
Exceptional Handling in Java
No comments:
Post a Comment