1

Sorry if title phrasing is bad, feel free to edit if need be.

Let's assume a Main Class, that creates an object from the class A, whose constructor receives an object from the class B as a parameter. One way to code it is :

B b = new B(); A a = new A(b);

Which would yield the following UML Sequence Diagram : Default Sequence

But now, let's say I want to code it in another way, so as to not keep a reference to the B object (make it anonymous), like this :

A a = new A(new B());

Which of the following UML Sequence Diagrams would it yield ?

First option (not changing the overall order of operations) : First

Second option (changing the order) : Second

In other words, would the B object be created by the Main class, or by A's constructor ?

Gael L
  • 243
  • 1
  • 11
  • The argument to the constructor, be it named or anonymous, is created by the object that invokes the constructor. Btw: it should be `:Main` (anonymous object of class Main), if Main is the name of a class. – Christophe Mar 11 '20 at 14:48
  • @Christophe Ahh, well, it assumes here that the main method is static (from the class Main itself). – Gael L Mar 11 '20 at 15:30
  • @Christophe I should have searched first. There are so many answers here which are more or less alike. – qwerty_so Mar 11 '20 at 16:02

2 Answers2

1

I ran a simple program with a debugger to watch when the new B object is created. It was created before the call to the constructor for a. Thus, the main class is creating it and then passing it into the constructor to create a.

Class A:

public class A()
{
    public A(B b)
    {
        //constructor stuff
    }  
}

Class B:

public class B()
{
    public B()
    {
        //constructor stuff
    }
}

Main

public class App()
{
    public static void main(String[] args)
    {
        A a = new A(new B());
    }
}
MrsNickalo
  • 207
  • 1
  • 6
1

Your first option is correct. The inner object B is created in main. Now A is created and the (anoymous) B object passed as parameter.

The 2nd option would mean that B is created inside A which isn't the case.

qwerty_so
  • 35,448
  • 8
  • 62
  • 86