Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Concept of Instantiate

 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone

I just gave an interview recently and faced a weird question on making an instance of a class.
Say, we are making an instance of a class A as follows :
A a = new A();

Que: What is meant by the " A() " term ? Though i know " new A() " will call the constructor of that class but he excluded the "new" in his question.

Thanks!!
 
Ahsan Bagwan
Ranch Hand
Posts: 252
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A() might be the default constructor (a no-arg constructor implicitly generated when no constructor is provided) or could be an explicitly provided no-arg constructor of the class. Since it cannot stand on its own when creating objects, you do need a new operator as you have already figured out. You then get reference to the object you just created and can then assign it to an object type, or use as it is like -



Please read http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html (unless I am mistaken what your question was).

If he excluded new, the compiler will reject the program.
 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks Ahsan!!!
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree with Ahsan, compile error occur without new operator. However, just to add, there are some object which can be created without new operator, for instance, String and array.
 
Campbell Ritchie
Sheriff
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahsan Bagwan wrote: . . . the default constructor (also called as no-arg constructor) of the class. . . .
That is confusing. A default constructor might have no arguments, but a default constructor and an ordinary no‑arguments constructor are different.
 
Ahsan Bagwan
Ranch Hand
Posts: 252
1
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the heads up Campbell. I have worded the sentence differently.
 
Campbell Ritchie
Sheriff
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Thank you.


Thank you Campbell!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic