FACTORY METHOD
Definition:- A factory method one whose return type is similar to the class name which class in the presents. The purpose of factory method to create an object of any class without using new operator. We have two types of factory methods. They are
1. Instance factory method
2. Static factory method
A nameless object does
not contain any name explicitly. A nameless object is also called
anonymous object.
Syntax
new classname( ).Instance
methodname();
note:- Nameless object approach concept is applicable for instance method only.
Q. How do you written an object of current class?
- Choose the appropriate class name.
- Choose the appropriate methods in the current class.
- Current class method must return ‘this’ which is nothing but object of current class.
- Current class method return type must be the name of current class.
Q. Define a java program by using the factory method and nameless object in java.
Program:-
class Test
{
Test display()
{
System.out.println("Hello java");
return this; // refers to current class object.
}
Test show()
{
System.out.println("Java4teachus");
return this;
}
Test write()
{
System.out.println("JavaTraining");
return this;
}
}
class NameLess
{
public static void main (String[ ] args)
{
System.out.println("Display the named object-----IM");
Test t1=new Test();
t1.display();
t1.show();
t1.write();
System.out.println("Display the nameless object------IM");
new Test().display().show();
}
}
{
String a;
Sathya set()
{
a="java4";
System.out.println("insert value="+a);
return this;
}
void increment()
{
a=a+"teachus";
System.out.println("increment value="+a);
}
}//sathya
class NameLess2
{
public static void main(String args[ ])
{
System.out.println("Write the named object------InstanceMember");
Sathya S =new Sathya();
S.set();
S.increment();
System.out.println("Write the nameless object-----InstanceMember");
new Sathya().set().increment();
}
}
Note:- “this” used must instance content but not in static context ( i.e. static block, static method).
No comments:
Post a Comment
Thanks for visiting my site..