When constructing a new object, I use the following code. In this code, is the object reference the variable 'a'?
BankAcc a = new BankAcc();
Also, out of interest, if the above constructs a new object to the variable a, what does the following do? Does it just create a new object without a variable/object reference?
new BankAcc();
Thanks!
Yes and yes.
The second one might be useful when you just want to use an anonymous object without caring about having a reference. Like:
new Thread(new Runnable() {
public void run () { }
}).start();
As explained in this Java tutorial, the creation of an object by using
BankAcc a = new BankAcc();
is a multi-step process. You have the declaration, instantiation and the initialization step
I will only highlight the most interesting parts from that tutorial which are relevant to your question:
To declare a variable, you use type name; (in this case BankAcc a;), which indicates a will/can be used to refer to data of type BankAcc. At this moment, a does not reference any object
To instantiate ayou use the new keyword. This will allocate memory for a new object and returning a reference to that memory. The new operator needs one single postfix argument: a call to a constructor. Whether or not you assign the reference returned by calling new to a variable or not is your choice. You can also use this reference directly in an expression (e.g. new Rectangle().height;)
The initialization is the actual call to the constructor, which initializes the new object. The constructor is invoked by the new operator
new BankAcc() creates the object and calls the constructor. Sometimes you need to do that, for example:
Rectangle rect = new Rectangle(new Point(100, 200), new Dimension(100, 300));
That is just an example of code so that you can see how it can be used.
Yes, it just creates object, but it won't be assigned to any reference, so you can't access that object and do any operations on that object. It will just stay there in memory until garbage collected.
Yes, and yes.
Note that just creating a new instance of a class without holding a reference to it is not unheard of (though not necessarily ideal), as the constructor of the class may do everything that is expected for a given operation.
The second line of code instantiate an anonymous instance of BankAcc class.
It is a quick way to instantiate a class,it is usually used when you need the reference only one time, for example to pass a class instance to a method argument :
myFunc(new BankAcc());
Yes the variable reference is "a" and yes new BankAcc(); creates a new object with no variable thus making it anonymous.
I think Sun some it up pretty nicely,
"The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor."
So yes a is a reference to the object BankAcc you instantiated with the new operator i.e. you are assigning = the return of new to the variable a which is a reference to an instance of type BankAcc
Regarding your second point, this can be done (compiled and executed) but I can't see many reasons why you would unless the constructor did something 'important'.
Edit: please refer to Tudor's answer for examples where instantiating without a reference is applicable
Object is a real time entity or real world entity.
Examples of object is pen,car,board,table,pencil etc.,
Suppose see your class name is Book.here how to we declare object
Book obj=new Book();
Related
I've one doubt about java reference type creation.
Suppose I've one class below
public class DefaultRepositorySelector
implements RepositorySelector
{
final LoggerRepository repository;
public DefaultRepositorySelector(LoggerRepository repository)
{
this.repository = repository;
}
public LoggerRepository getLoggerRepository()
{
return this.repository;
}
}
And am calling above class's constructor DefaultRepositorySelector somewhere in another class, like below.
repositorySelector = new DefaultRepositorySelector(new NOPLoggerRepository());
As you can see am Initializing a class new DefaultRepositorySelector(new NOPLoggerRepository()) and constructor accepts NOPLoggerRepository instance which is having an implementation of LoggerRepository Interface.
My doubt here is, we are directly passing a new NOPLoggerRepository() as a parameter in constructor which is an instance not a reference type, But constructor is holding a reference type LoggerRepository.
Am not able to understands the flow here, because according to flow when we are creating an instance we passing new object but not a reference to that object but in class's definition constructor accepts reference type of that object.
So at run time, How its taken care when we directly pass an instance but method or constructor accepts reference type of that instance ? Who gets created first reference type of OR Instance ? I think reference type but am not sure how its working behind the scenes..!
My question sounds very silly but please help to understand this ..!
Thanks
An object of class NOPLoggerRepository is created and passed to the method.
That's valid because NOPLoggerRepository implements LoggerRepository.
Rules about when an object is no longer reachable (and available for garbage collection) mean it won't be collected before being passed in (in case you were worrying about such weirdness).
When the constructor has completed the DefaultRespositorySelector holds a reference to the object passed in. However we know (in this case) it's underlying class is NOPLoggerRepository.
All good. The compiler knows when the underlying type may not be the explicit type of a reference and by various mechanisms ensures the correct behaviour. (Glossing over a whole load of stuff some implementation defined).
In java you never 'really' pass a object and class variables don't hold 'objects'.
They are always references to objects.
In casual conversation we all often say things like "I'm passing an NOPLoggerRespository to the constructor" but we really mean I'm passing a reference to a NOPLoggerRespository to the constructor. That's OK because it's always a reference so long as we all understand it's a fine shorthand.
I'm not quite sure I correctly understand your question.
You are going to create the object with the name repositorySelector of type DefaultRepositorySelector. While calling the constructor you need to have a reference of a LoggerRepository, which is a reference to a existing object (or null, if you pass null).
So, to get a reference, you pass new NOPLoggerRepository().
The expressions in parenthesis are evaluated first, so before the constructor of DefaultRepositorySelector can be called, the NOPLoggerRepository will be created as an anonymous object. That is, the object is created and is given no name. But we have the reference to it, which means we know where it is located on the heap.
As NOPLoggerRepository is of type LoggerRepository the constructor of DefaultRepositorySelector accepts the reference - the location of the anonymous object located on the heap and the object, which is named repositorySelector will be created.
Long story short, before calling a method (or constructor) the parameters are evaluated first (object creation, mathematical calculations, other method called and evaluated etc.), then the actual method can be called with the evaluated arguments.
The general idea of
Java is pass by Value
in objects does pretty much varie from premitive types .
in your code :
repositorySelector = new DefaultRepositorySelector(new NOPLoggerRepository());
the (new NOPLoggerRepository() is considered an Ignored Instance for the code scope in wich is invoked .
the thing in here is when you invoked the new DefaultRepositorySelector it did nothing at first as the parameters are invoked first , so in the ordered sequence
new NOPLoggerRepository() is invoked and created a new instance with no refrence on it on the heap .
new DefaultRepositorySelector is invoked and do ask for it's RepositorySelector instance wich is located with no any refrence in the example .
the JVM create the sole refrence for that object in your constructor and then another one (when your constructer pops off) in your class a .
so in short . it is still by refrence but just behind the scene .
What you're referring to is commonly known as dependency injection. First, the object that's being injected is instantiated, and then the dependent object. SO answer here.
I'm having confusion in calling a non-static method
class A {
void doThis() {}
public static void main(String... arg) {
A a1 = new A();
a1.doThis(); // method - 1
new A().doThis(); // method - 2
}
}
I know that both method-1 and method-2 will call doThis(), but is there any functional difference?
There won't be any difference in execution of those methods but in case of new A().doThis() your're going to lose the reference to the instance of an object you've invoked the method on and you won't be able to use it further in your code. All the changes this method could've done to internal state of the instance will be lost.
In case of A a1 = new A(); a1.doThis(); you're going to preserve the instance of an object (in variable a1) and potential changes made to its state made by method doThis(). Then you'll be able to continue working with this object.
Is there any functional difference?
Both will behave in the same way.
The second option doesn't allow you to reuse that instance again. It may be convenient and concise in one-line return statements (for instance, consider the builder pattern where each constructing method returns a half-initialised instance):
return new Builder().a().b().build();
or if an object was created only to perform a defined action once.
What will be the reference of a new object in method-2?
It is no longer exist (more precisely, we don't have access to it) unless the doThis returns this which you could be able to put in a variable after method execution.
Can I say that method-2 is an improper way of calling a non-static method?
No. Why should we create a variable if this variable will never be used afterwards?
Let's see what the code says in plain English:
A a1 = new A();
a1.doThis();
Create a new instance of A.
Store a reference to it in the variable a1.
Call doThis() on our instance.
Whereas new A().doThis(); reads as:
Create a new instance of A.
Call doThis() on our instance.
So the only difference is whether you store it in a local variable or not. If you don't use the value in the variable any more, then that difference doesn't matter. But if you want to call another method on the same object, let's say a1.doThat(), then you're in trouble with the second solution, as you haven't got a reference to the original instance any more.
Why would you want to use the same object? Because methods can change the internal state of the object, that's pretty much what being an object is about.
Lets take a look at both these methods one by one.
Method-1
A a1 = new A();
a1.doThis();
In method-1, you have a reference of newly created instance of A, i.e a1 and you can call as many methods on this instance of A using this reference a1. Basically you can reuse that particular instance of A by using its reference a1.
Method-2
new A().doThis();
However in method-2, you don't have any variable that stores the reference of your newly created instance of A. How will you refer to that particular instance of A if you have to call any other method on that particular instance of A ? You will not be able to re-use that instance of A if you create an instance using method-2 and you will lose that instance as soon as it is used.
case1:
A a1 = new A();
a1.doThis();
The above two line means object created and doThis(); executed but still object available in the heap memory.
case2:
new A().doThis();
A class object created and doThis(); executed after immediately GC(GarbageColletor) will activate to remove the A object from the heap memory bcz it's a non-referenced object and we can call this object as an anonymous object.
When we create a new object in Java, we use the syntax:
ClassName instancename = new ClassName();
My question is why do we have to type the class name at the beginning? Why is there simply not an 'object' keyword?
Example:
object instancename = new ClassName();
On the left hand:
ClassName instancename
The ClassName is declaring type (= class) of variable instancename.
On the right hand:
new ClassName();
The ClassName() is invoking a (constructor) method named ClassName().
So, you are doing two things at once.
ClassName instancename; // declaring type
instancename = new ClassName(); // invoking method
Your example:
ClassName instancename = new ClassName();
is just shortened style of the two instructions.
There are other styles of getting an instance of a class -- newInstance() or getInstance() for example.
That is: declaration of type and method of instantiation are the separate things. They are needed for their own purposes.
Object is the parent class for all java classes. When you call the class the first time,
ClassName instancename
it creates memory reference for that variable name, but that reference isn't pointing to an actual object yet since it hasn't been created in memory. When you call it the second time,
instancename = new ClassName();
it calls ClassName's default constructor which allocates memory and actually creates the object in memory.
It's safer to create an instance of ClassName instead of object when working with multiple classes. If you use object to declare your classes, you will often have to frequently use typecasting so your code will compile because the compiler will know which class to look at to find the corresponding class's method.
My question is why do we have to type the class name at the beginning? Why is there simply not an 'object' keyword?
You are doing two "things", you are creating a reference that can hold a ClassName, and creating an instance of ClassName.
Many languages can infer one side from the other however Java (by default, see Lombok) can not. From memory with was originally done this way to keep the language specification simple.
There are many new languages out there that can intuit the types of created objects. Java is one of them.
new ArrayList<String> ()
Java knows the type of the result is ArrayList<String>. However, in Java, you do not have to assign the result to an object of that type, you can use any type in the hierarchy all the way up to Object - in fact you are even encouraged to do so. Most commonly you would move up to the nearest interface (List<String> in this case) but going further up can be useful (Iterable<String> would work well here). The recommended technique in this case would be:
List<String> myList = new ArrayList<String> ();
or - more succinctly in Java 7
List<String> myList = new ArrayList<> ();
or
Iterable<String> myList = new ArrayList<> ();
Had a conversation with a coworker the other day about this.
There's the obvious using a constructor, but what are the other ways there?
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.
There are various ways:
Through Class.newInstance.
Through Constructor.newInstance.
Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
Through Object.clone (does not call a constructor).
Through JNI (should call a constructor).
Through any other method that calls a new for you.
I guess you could describe class loading as creating new objects (such as interned Strings).
A literal array as part of the initialisation in a declaration (no constructor for arrays).
The array in a "varargs" (...) method call (no constructor for arrays).
Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
Oh, and boxing of primitives (unless cached), of course.
JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
For completeness (and Paŭlo Ebermann), there's some syntax with the new keyword as well.
Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.
Yes, you can create objects using reflection. For example, String.class.newInstance() will give you a new empty String object.
There are five different ways to create an object in Java,
1. Using new keyword → constructor get called
Employee emp1 = new Employee();
2. Using newInstance() method of Class → constructor get called
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor → constructor get called
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone() method → no constructor call
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization → no constructor call
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
First three methods new keyword and both newInstance() include a constructor call but later two clone and deserialization methods create objects without calling the constructor.
All above methods have different bytecode associated with them, Read Different ways to create objects in Java with Example for examples and more detailed description e.g. bytecode conversion of all these methods.
However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.
Cloning and deserialization.
Also you can use
Object myObj = Class.forName("your.cClass").newInstance();
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
Also, you can de-serialize data into an object. This doesn't go through the class Constructor !
UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.
It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.
Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java
There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with
A[] array = new A[len];
or
A[] array = new A[] { value0, value1, value2 };
As Sean said in a comment, this is syntactically similar to a constructor call and internally it is not much more than allocation and zero-initializing (or initializing with explicit content, in the second case) a memory block, with some header to indicate the type and the length.
When passing arguments to a varargs-method, an array is there created (and filled) implicitly, too.
A fourth way would be
A[] array = (A[]) Array.newInstance(A.class, len);
Of course, cloning and deserializing works here, too.
There are many methods in the Standard API which create arrays, but they all in fact are using one (or more) of these ways.
Other ways if we are being exhaustive.
On the Oracle JVM is Unsafe.allocateInstance() which creates an instance without calling a constructor.
Using byte code manipulation you can add code to anewarray, multianewarray, newarray or new. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.
Reflection:
someClass.newInstance();
Reflection will also do the job for you.
SomeClass anObj = SomeClass.class.newInstance();
is another way to create a new instance of a class. In this case, you will also need to handle the exceptions that might get thrown.
using the new operator (thus invoking a constructor)
using reflection clazz.newInstance() (which again invokes the constructor). Or by clazz.getConstructor(..).newInstance(..) (again using a constructor, but you can thus choose which one)
To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
There are FIVE different ways to create objects 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.
MyObject object = new MyObject();//normal way
2. By Using Factory Method:
ClassName ObgRef=ClassName.FactoryMethod();
Example:
RunTime rt=Runtime.getRunTime();//Static Factory Method
3. By Using Cloning Concept:
By using clone(), the clone() can be used to create a copy of an existing object.
MyObjectName anotherObject = new MyObjectName();
MyObjectName object = anotherObjectName.clone();//cloning Object
4. 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.
MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();
Example:
String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );
MyObjectName object = (MyObjectNmae) inStream.readObject();
You can also clone existing object (if it implements Cloneable).
Foo fooClone = fooOriginal.clone ();
Method 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.
Employee object = new Employee();
Method 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 (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();
Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).
Another must read:
Java: Thread State Introduction with Example
Simple Java Enum Example
Method 3
Using clone(). The clone() can be used to create a copy of an existing object.
Employee secondObject = new Employee();
Employee object3 = (Employee) secondObject.clone();
Method 4
Using newInstance() method
Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();
Method 5
Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.
// Create Object5
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(object3);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
Employee object5 = (Employee) ois.readObject();
From an API user perspective, another alternative to constructors are static factory methods (like BigInteger.valueOf()), though for the API author (and technically "for real") the objects are still created using a constructor.
Depends exactly what you mean by create but some other ones are:
Clone method
Deserialization
Reflection (Class.newInstance())
Reflection (Constructor object)
there is also ClassLoader.loadClass(string) but this is not often used.
and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.
We can create an objects in 5 ways:
by new operator
by reflection (e.g. Class.forName() followed by Class.newInstance())
by factory method
by cloning
by reflection api
We can also create the object in this way:-
String s ="Hello";
Nobody has discuss it.
Had a conversation with a coworker the other day about this.
There's the obvious using a constructor, but what are the other ways there?
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.
There are various ways:
Through Class.newInstance.
Through Constructor.newInstance.
Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
Through Object.clone (does not call a constructor).
Through JNI (should call a constructor).
Through any other method that calls a new for you.
I guess you could describe class loading as creating new objects (such as interned Strings).
A literal array as part of the initialisation in a declaration (no constructor for arrays).
The array in a "varargs" (...) method call (no constructor for arrays).
Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
Oh, and boxing of primitives (unless cached), of course.
JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
For completeness (and Paŭlo Ebermann), there's some syntax with the new keyword as well.
Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.
Yes, you can create objects using reflection. For example, String.class.newInstance() will give you a new empty String object.
There are five different ways to create an object in Java,
1. Using new keyword → constructor get called
Employee emp1 = new Employee();
2. Using newInstance() method of Class → constructor get called
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor → constructor get called
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone() method → no constructor call
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization → no constructor call
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
First three methods new keyword and both newInstance() include a constructor call but later two clone and deserialization methods create objects without calling the constructor.
All above methods have different bytecode associated with them, Read Different ways to create objects in Java with Example for examples and more detailed description e.g. bytecode conversion of all these methods.
However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.
Cloning and deserialization.
Also you can use
Object myObj = Class.forName("your.cClass").newInstance();
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
Also, you can de-serialize data into an object. This doesn't go through the class Constructor !
UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.
It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.
Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java
There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with
A[] array = new A[len];
or
A[] array = new A[] { value0, value1, value2 };
As Sean said in a comment, this is syntactically similar to a constructor call and internally it is not much more than allocation and zero-initializing (or initializing with explicit content, in the second case) a memory block, with some header to indicate the type and the length.
When passing arguments to a varargs-method, an array is there created (and filled) implicitly, too.
A fourth way would be
A[] array = (A[]) Array.newInstance(A.class, len);
Of course, cloning and deserializing works here, too.
There are many methods in the Standard API which create arrays, but they all in fact are using one (or more) of these ways.
Other ways if we are being exhaustive.
On the Oracle JVM is Unsafe.allocateInstance() which creates an instance without calling a constructor.
Using byte code manipulation you can add code to anewarray, multianewarray, newarray or new. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.
Reflection:
someClass.newInstance();
Reflection will also do the job for you.
SomeClass anObj = SomeClass.class.newInstance();
is another way to create a new instance of a class. In this case, you will also need to handle the exceptions that might get thrown.
using the new operator (thus invoking a constructor)
using reflection clazz.newInstance() (which again invokes the constructor). Or by clazz.getConstructor(..).newInstance(..) (again using a constructor, but you can thus choose which one)
To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
There are FIVE different ways to create objects 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.
MyObject object = new MyObject();//normal way
2. By Using Factory Method:
ClassName ObgRef=ClassName.FactoryMethod();
Example:
RunTime rt=Runtime.getRunTime();//Static Factory Method
3. By Using Cloning Concept:
By using clone(), the clone() can be used to create a copy of an existing object.
MyObjectName anotherObject = new MyObjectName();
MyObjectName object = anotherObjectName.clone();//cloning Object
4. 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.
MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();
Example:
String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );
MyObjectName object = (MyObjectNmae) inStream.readObject();
You can also clone existing object (if it implements Cloneable).
Foo fooClone = fooOriginal.clone ();
Method 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.
Employee object = new Employee();
Method 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 (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();
Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).
Another must read:
Java: Thread State Introduction with Example
Simple Java Enum Example
Method 3
Using clone(). The clone() can be used to create a copy of an existing object.
Employee secondObject = new Employee();
Employee object3 = (Employee) secondObject.clone();
Method 4
Using newInstance() method
Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();
Method 5
Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.
// Create Object5
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(object3);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
Employee object5 = (Employee) ois.readObject();
From an API user perspective, another alternative to constructors are static factory methods (like BigInteger.valueOf()), though for the API author (and technically "for real") the objects are still created using a constructor.
Depends exactly what you mean by create but some other ones are:
Clone method
Deserialization
Reflection (Class.newInstance())
Reflection (Constructor object)
there is also ClassLoader.loadClass(string) but this is not often used.
and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.
We can create an objects in 5 ways:
by new operator
by reflection (e.g. Class.forName() followed by Class.newInstance())
by factory method
by cloning
by reflection api
We can also create the object in this way:-
String s ="Hello";
Nobody has discuss it.