What happens when you create a new object?

前端 未结 10 2348
梦谈多话
梦谈多话 2021-02-10 18:39

Ok, so what happens when you do this.

A a1=new A();

A a2=new A();

A a3=new A();

I upload two pictures on how I imagine it being like. Can you

相关标签:
10条回答
  • 2021-02-10 19:18

    First picture is true for Strings( due to string pooling, an optimisation for strings known to be identical at compile time):

    String a1="s";
    String a2="s";
    String a3="s";
    

    The second one is true for:

    A a1=new A();
    A a2=new A();
    A a3=new A();
    

    If you want behaviour like String has - you should implement Flyweight pattern.

    0 讨论(0)
  • 2021-02-10 19:18

    The second picture is correct. Each of the three statements is creating a reference (A a1 =), and an actual object in memory (new A()). Throw out the first picture :)

    0 讨论(0)
  • 2021-02-10 19:20

    Go through the images, hope this helps.

    Refer Image

    Refer image

    0 讨论(0)
  • 2021-02-10 19:27

    Whenever you see a

    ABC a1 = new ABC();
    

    it means a new object is created and using a1 you can access it.

    It is exactly similar to going to a bike shop and aking them to get a *new bike *. Every time you say new they will get a new bike for you.

    Meaning of both sides:

    Right side means you have a new object of type on the right side.

    The left side says you want to keep a variable of type on the left side.

    So you can have different types of both sides but there is a contract or condition that you have to take care. The condition is that the type on the left side should be either a super class of the type on the right side or the left side is an interface and the right side type implements it.

    Example:

    A a1 = new AB();
    A a2 = new BC();
    

    and both AB and BC either are subclass of A or A is an interface which will be implemented.

    Now after creating an object when you assign it to the left side is exactly similar to having a baloon (newely created object) and attaching a string (a1) to it. This way you can attach multiple string to one baloon i.e.,

    A a1 = new A();
    A a2 = a1;
    

    Bithe a1 and a2 point to the same object.

    0 讨论(0)
提交回复
热议问题