This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructers in java  RSS feed

 
smyle khanna
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..
i have 2 programs such tht:this is the first program

the second program is:


when i compiled this program..the second program gives errors
but if i use a construct it doenst give.

can any1 tell me the reason as to y it didnt compile b4 n then later it complied.
is it necessary tht a class must havea default constructs?
thanks in advance
Smyle
 
Eddie Vanda
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is a class with code not in a method nor constructor, so no compile.


This code is in a method (happens to be a constructor) so compiles ok.
 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by smyle khanna:
is it necessary tht a class must havea default constructs?
thanks in advance
Smyle[/QB]


It is not necessary for a class to have a explicitly declared default constructor. If you do not specify one, the compiler will generate a default constructor for you. For example, you could have the following code for your example:




Although there is no explicit constructor, the compile will generate one that looks like:

public Second() {};

The above code is an example of a static initializer that executes when the class itself loads before object instantiation (and thus, the constructor) occurs.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your first program, you're not instantiating a new object at all! Unless you've a typo here...



Not



If you've the latter, I don't think the compiler will be nice to you
 
Kaustubh Patil
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Smyle,

The compilation gives error because.. the code
"second a=new second;"
is not assosciated with any method or is static. If you do not want to put it in any method put it in a static block. this will associate it with the class and not any instance of that class.
put it like this
"
static{
second a=new second;"
}"

It will compile.
Happy compiling.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!