There are four ways to create a Object in Java. They are
1. Using new keyword - This is the most common way to create an object in java.
Example:
MyObject object = new MyObject();
2. Using Class.forName() - If we know the name of the class and if it has a public default constructor we can create an object in this way.
Example:
MyObject object = (MyObject) Class.forName("com.ranga.MyObject").newInstance();
3. Using clone() - The clone() can be used to create a copy of an existing object.
Example:
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
4. Using object deserialization - Object deserialization is nothing but creating an object from its serialized form.
Example:
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Sunday, May 17, 2015
What are all the different ways to create an object in Java?
Related Posts:
Difference Between ClassNotFoundException and NoClassDefFoundErrorClassNotFoundException (java.lang.ClassNotFoundException): ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class.public class ClassNotFoundException extends Exc… Read More
Dynamic Array Example in JavaDynamicArrayExample.javapackage com.ranga;/** * * This program demonstrates the creating dynamic arrays. * User: ranga * Date: 11/14/13 * Time: 4:40 PM */class DynamicArray { // the v… Read More
Hibernate4.X Application example by using GradlePrerequisite requirement - Installed and configured Maven, MySQL, Eclipse IDE.- See more at: http://www.developer.am/documentation/hibernate/?page=maven-spring-hibernate-mysql-example#sthash.8UVHMaBr.dpufPrerequisite requirem… Read More
Developing a Sample HelloWorld Java Program by using MavenStep1: Create a HelloWorld java project by using mvn command.[ranga@ranga Documents]$ mvn archetype:generate -DgroupId=com.ranga -DartifactId=HelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false… Read More
Difference between Abstraction and EncapsulationIn Java both Abstraction and Encapsulation are two important OOP (Object Oriented Programming) concepts or principles. Both are completely different from each other. Abstraction(Hiding): Abstraction means hiding.Abstra… Read More
0 comments:
Post a Comment