What are all the different ways to create an object in Java?
There are four different ways to create objects in java:
A. Using new
keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
B. 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();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
D. 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();
You can read them from here.
Ways to create objects in Java
According to here, you can create Java objects as follows:
- 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();
- 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();
- Using clone() The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); MyObject object =
anotherObject.clone();
- 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();
How can I make an object using another object in Java?
You can define a new method in Dog
class:
public Dog createTheSameAgeDog(String name) {
return new Dog(name, this.age);
}
Then call it:
Dog dog3 = dog2.createTheSameAgeDog("Krypto"); // creates the Dog (age 7, name "Krypto")
How to create object of class
You should use a constructor:
public class Model {
//Constructor
public Model()
{
// Do initialization stuff here
}
}
public class UserModel extends Model {
//Constructor
public UserModel()
{
// Do initialization stuff here
}
}
To create new object, you call it like that:
UserModel myUserModel; // Declare new object reference
myUserModel = new UserModel(); // create new object of this class
Edit:
If you declare the method as a method returning array of Model
s, you can't return a single model, you may return a Model
array with one Model
, but not a single object.
For example
public static Model [] findAllBySQL(String SQL){
// find how many models do you have
Model[] models = new Model[numberOfModels];
for (Model model : models)
{
model = new Model();
//do what you want with it...
}
return models; //sytax error here
}
Most maintainable and readable way to create objects with many fields
I would prefer combining the already mentioned solutions - as you write in your intro "I'm creating a Java class that should encapsulate the six orbital elements of a celestial object, the six osculating elements of the same element, the mass of the body and the name of the body.", it seems to me that you can group each six parameters into a new datastructure, so that you end up with four parameters for the Planet
constructor (name, mass and the two parameter objects with six own values each) - next step I would ask myself if the six orbital and osculating elements somehow carry extra meaning or are merely a group of six (as in "arbitrary number") elements and can therefore be represented as a list.
Create different objects depending on type
You can use
Object o = Class.forName(type).newInstance();
If you have an int and two Strings as arguments you need.
Object o = Class.forName(type)
.getConstructor(int.class, String.class, String.class)
.newInstance(intValue, string1, string2);
Another possibility is to use factory methods
Object o = getClass().getMethod("create_" + type).invoke(null);
static Object1 create_object1() {
return new Object1(/* with args */);
}
static Object2 create_object2() {
return new Object2(/* with other args */);
}
but the most flexible approach may be to use a switch
Object o;
switch(type) { // in Java 7
case "object1": o = new Object1(); break;
case "object2": o = new Object2(); break;
What would be more elegant is using closures in Java 8.
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
How to create an object of one class with arguments of another? Java
You need to pass a Date object! Take a look at this sample:
Date date1 = new Date(1, 5, 1995);
Date date1 = new Date(1, 6, 2011);
Employee e = new Employee("Tom" , "Doe",date1, date2 );
Now you are passing the two references of a Date object to the Employee constructor. You could even do this:
Employee e = new Employee("Tom" , "Doe", new Date(1, 5, 1995), new Date(1, 6, 2011));
Related Topics
Spring: @Component Versus @Bean
Using Env Variable in Spring Boot's Application.Properties
Is There a Destructor for Java
Where Is Array's Length Property Defined
Connecting to Remote Url Which Requires Authentication Using Java
Java: Define Terms Initialization, Declaration and Assignment
How Will Java Lambda Functions Be Compiled
Calling a Subclass Method from Superclass
Java and Gui - Where Do Actionlisteners Belong According to MVC Pattern
Java Comparison with == of Two Strings Is False
When and How to Use a Threadlocal Variable
Using Setdate in Preparedstatement
Differences Between Oracle Jdk and Openjdk
What Is the Point of "Final Class" in Java