What is the Java UML Sequence order when passing an anonymous object as parameter?

685 Views Asked by At

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 ?

2

There are 2 best solutions below

0
MrsNickalo On

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());
    }
}
0
qwerty_so On

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.