-2

I am confused about this syntax:

ImageTests ttpanel=new ImageTests();

 // create a JFrame to hold the test JPanel
 JFrame app = new JFrame("Image Tests");
 app.getContentPane().add(ttpanel, BorderLayout.CENTER);

ImageTests is another class whose constructor creates a JPanel. Therefore, does an object always references its constructors when it is not ordered to reference some other method? In short, does an unreferenced object automatically references the constructors? I have never seen this kind of syntax before.

Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48
Soumil
  • 51
  • 9
  • 4
    I'm not sure I fully understand your question. Basically, ttPanel is already constructed and the app.getContentPane().add() method is just getting passed a reference to the ttPanel object. – Michael Markidis May 23 '16 at 05:38
  • 1
    Possible duplicate of [When does the Constructor gets called in java?](http://stackoverflow.com/questions/9567341/when-does-the-constructor-gets-called-in-java) – Yassin Hajaj May 23 '16 at 05:41
  • *"I have never seen this kind of syntax before."* Me neither. Having two variables `ttpanel` and `ttPanel` that differ only by the upper-/lower-case of the `P` is horrendous!!! And the class names `ImageTests` vs `ImagesTests`. Yeah, I have never seen bad code that that before, either. – Andreas May 23 '16 at 05:48
  • At first there was a mistake in the question. I have corrected it. – Soumil May 23 '16 at 06:22
  • `new ImageTests()` and `new JFrame("Image Tests")` are both constructors. Your question remains unclear. – user207421 May 23 '16 at 08:15
  • My question is, does an unreferenced object automatically references the constructors? – Soumil May 24 '16 at 05:22

1 Answers1

0

A constructor is only called once in the life time of an object, it is called only when the object is created. When you use new.

eg.

MyClass myclass = new MyClass();

When an object of MyClass is created the constructor of MyClass will be executed.

BMW
  • 42,880
  • 12
  • 99
  • 116