How many ways we can create object in java?:
===================================
===================================
We can create object in java in 5 ways:
1. By using NEW keyword
2. By using new Instance (Reflection API)
3. By using clone() method
4. By using Deserilization
5. By using class loader
1. By using new Keyword: Most commonly we use create object
in java by using new keyword
Whenever we use new in java object is going to be created
package com.rameshsoft.keys;
public class Test {
String
name = "RAMESHSOFT";
public void hello() {
System.out.println("WELCOME
TO RAMESHSOFT: " +name);
System.out.println("MASTERS
IN JAVA WITH SELENIUM REAL TIME: " +name);
}
public static void main(String[] args) {
//creating
object using new keyword
Test
test = new Test();
test.hello();
}
}
2.By using clone() method
We can create object using clone() method as well. this
method is present in Object class(java.lang.Object)
syntax of clone() method:
public Object clone();
package com.rameshsoft.keys;
public class Test {
String
name = "RAMESHSOFT";
public void hello() {
System.out.println("WELCOME
TO RAMESHSOFT: "+name);
System.out.println("MASTERS
IN JAVA WITH SELENIUM REAL TIME: " +name);
}
public static void main(String[] args) throws
CloneNotSupportedException {
//creating
object using new keyword
Test
test = new Test();
//creating
cloned object using clone() method
Test
testClone = (Test)test.clone();
testClone.hello();
}
}
3. 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.
Syntax:
Test test=(Test)
class.forName("JDBC.........").newInstance();
4. using object deserialization
Object deserialization
is nothing but creating an object from its serialized form.
Syntax:
ObjectInputStream
istream=new ObjectInputStream(some data);
Test test=(Test)
instream.readObject();
5. By using class loader