Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role of new keyword in Java

Tags:

java

I am not sure how new keyword behaves in Java. Is it for sure that every time I will use new keyword, a new Object will be created on heap?

I got this doubt when I was studying following example-

class Mixer {
  Mixer() { }
  Mixer(Mixer m) { m1 = m; }
  Mixer m1;
  public static void main(String[] args) {
    Mixer m2 = new Mixer();
    Mixer m3 = new Mixer(m2); // Does it create any new mixer object?
    m3.go();
    Mixer m4 = m3.m1;          m4.go(); 
    Mixer m5 = m2.m1;          m5.go();
  }
  void go() { System.out.print("hi "); }
}

The line Mixer m3 = new Mixer(m2); invokes a constructor which does not create any new object. So, is it that no new object was created?

Also, Which variable refers to which object in the end of program, i.e. till we get NullPointerExcetion for variable m5.

like image 524
Prateek Singla Avatar asked Jun 05 '13 14:06

Prateek Singla


Video Answer


1 Answers

Yes - every time you use new (as a keyword) a new object will be created. In this case:

Mixer m3 = new Mixer(m2);

The line Mixer m3 = new Mixer(m2); invokes a constructor which does not create any new object.

Your reasoning is completely incorrect. A new Mixer is being created using m2 as a parameter. Usually this indicates a copy constructor - creating a new Mixer with the same properties as the old one (but it is always a new, distinct object, and doesn't technically have to copy the properties of the object passed in at all.)

like image 108
Michael Berry Avatar answered Sep 29 '22 07:09

Michael Berry