Static Pre Define Factory Method
In this I created one class "SBToS" and in this we have two non-static pre defined factory methods toString() and substring() as shown below :-
SBToS.java
class SBToS{
public static void main(String arg[] ){
StringBuffer sb1 = new StringBuffer("Coding Atharva"); /* Mutable */
String s1 = sb1.toString(); /* IMMutable */
System.out.println("sb1: "+sb1);
System.out.println("s1: "+s1);
String s2 = sb1.substring(7);
System.out.println("s2: "+s2);
String s3 = sb1.substring(0,6);
System.out.println("s3: "+s3);
}
}
Non Static Pre Define Factory Method
In this I am using the newinstance() method and we have two classes "A.java" and "B.java" and when we are sending this class name from command line argument it will print the data.
A.java
class A
{
int a = 111;
}
B.java
class B
{
int b = 222;
}
NewinstanceDemo.java
class NewinstanceDemo
{
public static void main( String s[] )
throws ClassNotFoundException,InstantiationException,IllegalAccessException{
java.lang.Class cls = Class.forName(s[0]);
Object o = cls.newInstance();
if(o instanceof A)
{
System.out.println("A class object");
A obj1 = (A)o;
System.out.println(obj1.a);
}
else if(o instanceof B)
{
System.out.println("B class object");
B obj1 = (B)o;
System.out.println(obj1.b);
}
}
}
In this I created one class "SBToS" and in this we have two non-static pre defined factory methods toString() and substring() as shown below :-
SBToS.java
class SBToS{
public static void main(String arg[] ){
StringBuffer sb1 = new StringBuffer("Coding Atharva"); /* Mutable */
String s1 = sb1.toString(); /* IMMutable */
System.out.println("sb1: "+sb1);
System.out.println("s1: "+s1);
String s2 = sb1.substring(7);
System.out.println("s2: "+s2);
String s3 = sb1.substring(0,6);
System.out.println("s3: "+s3);
}
}
Output:
Non Static Pre Define Factory Method
In this I am using the newinstance() method and we have two classes "A.java" and "B.java" and when we are sending this class name from command line argument it will print the data.
A.java
class A
{
int a = 111;
}
B.java
class B
{
int b = 222;
}
NewinstanceDemo.java
class NewinstanceDemo
{
public static void main( String s[] )
throws ClassNotFoundException,InstantiationException,IllegalAccessException{
java.lang.Class cls = Class.forName(s[0]);
Object o = cls.newInstance();
if(o instanceof A)
{
System.out.println("A class object");
A obj1 = (A)o;
System.out.println(obj1.a);
}
else if(o instanceof B)
{
System.out.println("B class object");
B obj1 = (B)o;
System.out.println(obj1.b);
}
}
}
Output: