What happens when you create a new object?

前端 未结 10 1143
一个人的身影
一个人的身影 2021-02-10 18:53

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:25

    This is a variable declaration;

    A a1;
    

    You declare a new variable called a1 of type A.

    a1 = new A();
    

    You assign to a1 the value that results from new A(), which is a new object of type A.

    You can do both things at once as an initialization:

    A a1 = new A();
    

    Each time you call your class constructor, you get a different and separated instance of your class. No instances know about the others, they lie in different regions of memory.

    By the way, those are very very basics of programming, so get a good reading and happy learning.

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

    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)
  • 2021-02-10 19:28

    2nd picture is correct.

    writing new is always create a newly object in heap.

    in real world comparison

    A a=new A();

    the above code can be similar to

    new A() ------------------ birth of a child

    A a ------------------ naming of that child(i.e. Ram,John)

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

    2nd one is correct because whenever an object is created, it´s constructor is being called only once.

    Here the three different objects are created by the constructor calls. So the constructor is called three times.

    Whereas an ordinary object method may be called any number times for a given object, not the constructor.

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