Java4teachus

Tuesday, June 18, 2019

Define Factory method and NameLess Object or annaymous object in java

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
Factory-Metod-and-nameless-Objec- in-java.jpeg

➤ Define Nameless object or anonymous class object

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();
    }
}
Output :
factory-method-program-or-nameless-object-in-java.jpeg


Source code:

class Sathya
{
    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..