8 Replies Latest reply: Nov 30, 2010 2:49 AM by 819746 RSS

    Methods that return an instance of their class/ Constructor question

    800736
      Hi,

      I'm studying for a CS exam and I came across an example in my book that is somewhat confusing. Let's say we have a class Name that contains a method setName that returns a Name object:

      public Name setName(String nameIn)
      {

      this.firstName = nameIn;
      return this;

      }


      Now the book refers to using this method as follows:

      Name bob = new Name();
      Name myBuddy = bob.setName("Bob");

      So my question is, would this code would cause 'myBuddy' to just be an alias of 'bob', just a different pointer to the Name instance that 'bob' reperesents?

      Thanks.
        • 1. Re: Methods that return an instance of their class/ Constructor question
          796440
          So my question is, would this code would cause 'myBuddy' to just be an alias of 'bob', just a different pointer to the Name instance that 'bob' reperesents?
          Yes.

          Just like any assignment to a reference type--that is, anything but a primitive or null---it is just another reference pointing to the same object.
          • 2. Re: Methods that return an instance of their class/ Constructor question
            796367
            Gentlemen, the proof is in the pudding... the Name class definition.
            public class Name implements Cloneable
            {
              public String name;
            
              public Object clone()
              {
                return this;
              }
            
              public String toString()
              {
                return "Name[" + name + ", " + hashCode() + "]";
              }
            }
            Now test the class...
            public class test
            {
              public static void main(String[] args)
              {
                Name myName = new Name();
                Name yourName = (Name)myName.clone();
                Name hisName = (Name)yourName.clone();
                Name herName = (Name)hisName.clone();
            
                yourName.name = "Bob";   // set any Name object
            
                System.out.println(myName);  // Name[Bob, 17237886]
                System.out.println(yourName);// Name[Bob, 17237886]
                System.out.println(hisName); // Name[Bob, 17237886]
                System.out.println(herName); // Name[Bob, 17237886]
            
                herName.name = "Cheryl"; // set any Name object
            
                System.out.println(myName);  // Name[Cheryl, 17237886]
                System.out.println(yourName);// Name[Cheryl, 17237886]
                System.out.println(hisName); // Name[Cheryl], 17237886
                System.out.println(herName); // Name[Cheryl, 17237886]
              }
            }
            This proves OP's assumption and jverd's assertion.

            Edited to include the hashcode in the output.
            • 3. Re: Methods that return an instance of their class/ Constructor question
              796440
              pierrot_2 wrote:
              This proves OP's assumption and jverd's assertion.

              Edited to include the hashcode in the output.
              Neither hashCode nor the contents prove anything. Totally different objects with totally different contents can have the same hashCode. If you want to prove that two reference variables point to the same object, use
              var1 == var2
              • 4. Re: Methods that return an instance of their class/ Constructor question
                796367
                Blimey... scally-wagged again.
                • 5. Re: Methods that return an instance of their class/ Constructor question
                  aksarben
                  A somewhat more interesting question, IMHO, is why would a programmer write a method that returns a refernce to the class instance? As you gain more experience, you'll find one of the more frequent reasons is convenience: By returning a reference to the object, it lets you chain method successive method calls into a single statement. This can shorten code, and often improve readability. And Java is not the only place this happens. The well known Javascript library Jquery makes heavy use of call chaining.

                  FYI
                  • 6. Re: Methods that return an instance of their class/ Constructor question
                    643310
                    aksarben wrote:
                    A somewhat more interesting question, IMHO, is why would a programmer write a method that returns a refernce to the class instance? As you gain more experience, you'll find one of the more frequent reasons is convenience: By returning a reference to the object, it lets you chain method successive method calls into a single statement. This can shorten code, and often improve readability. And Java is not the only place this happens. The well known Javascript library Jquery makes heavy use of call chaining.

                    FYI
                    Interesting point! But I couldn't understand how "myref.clone().someMethod()" is convenient than "myref.someMethod()". Could you please explain with an illustration on how the code is shortened?

                    On a different note, I wouldn't have named the method that returns the same instance as "CLONE". :-)

                    Edited by: vijay on Nov 17, 2010 10:49 PM
                    • 7. Re: Methods that return an instance of their class/ Constructor question
                      jwenting
                      aksarben wrote:
                      A somewhat more interesting question, IMHO, is why would a programmer write a method that returns a refernce to the class instance? As you gain more experience, you'll find one of the more frequent reasons is convenience: By returning a reference to the object, it lets you chain method successive method calls into a single statement. This can shorten code, and often improve readability. And Java is not the only place this happens. The well known Javascript library Jquery makes heavy use of call chaining.
                      That's one reason.
                      Another reason is to only allow a limited number of instances to exist.
                      The most common of this is the factory method returning a single instance of a class held as a private field of the class and created using a private constructor.

                      But it could also be used to draw an instance from a small pool of available instances.
                      Example could be a server that allows a limited number of connections, and holds a pool of client handlers created at startup which it hands out on a come as you go basis to connecting clients.
                      This can have an advantage of speeding up runtime behaviour at the cost of increased startup time for heavy object instantiation.
                      • 8. Re: Methods that return an instance of their class/ Constructor question
                        819746
                        Name bob = new Name();
                        Name myBuddy = bob.setName("Bob");

                        In this code bob and myBuddy refers to same object.
                        You can check it as follows

                        if(bob==myByddy)
                        {
                        //both references refer same object .
                        }
                        else
                        {
                        //not referring the same object.
                        }