Can we create an object with out using 'new' keyword in java?
Printable View
Can we create an object with out using 'new' keyword in java?
yeah in case of Strings we can create a new object by using the below given statement
String str = "Test_String";
this will create a new String object and the reference variable str will refer to that object. the value of that object will be Test_String
ya this is only possible with strings.
String is a class in Java.
You can create java String object using new.
String str=new String("");
String str="erer";
Both ways create String object.
Hope iam clear
[QUOTE=ani_lavanya;11215]Can we create an object with out using 'new' keyword in java?[/QUOTE]
Yes we can create object without using new
1.clone()
2.newinstance() in java.lang.class
[QUOTE=ani_lavanya;11215]Can we create an object with out using 'new' keyword in java?[/QUOTE]
Yes, Thats quite possible using the factory methods or using Creational Patterns.
Hi lavanya we can create object without using new opearator.
1) Using factory methods
Ex:- NumberFormat obj=NumberFormat.getInstance();
2)Using newInstance() method
Ex:-
Class c=Class.forName("SomeClassName");
SomeClassName obj=c.newInstance();
3)using cloning
Ex:- ClassName c1=new ClassName();
ClassName c2=c1.clone();
yes,we can create the object in 3 ways without using 'new' keyword
1)by calling clone() which has present in Object super class
2)using factory methods,we can get the same type of the object
Ex:take Calender class which is in java.util package,we will get the object of Calender class in following way
Calender objCal = Calender.getInstance(); here getInstance() is factory method
3)using newInstance() ,we can Create a new instance of the class represented by this Class object
Ex:Class objClass=Class.forName("Driverclass name");//objClass is the Class object for the class with the specified name
Object obj=objClass.newInstance(); and then type cast into our class and use that object
Yes, without using New keyword u can create objects in Java