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

Why should we invoke empty construtor even it doesn't need object?  RSS feed

 
prabhajan prabha
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have seen one program, in that the empty class constructor called on main method, why should we call that? even it has several public methods?
In java, the construtor invoked automatically, but here why should we call within that or why should we create object for the class without the variable? kindly clear my doubt

here is the code format.

public class Sample
{
public Sample()
{
}
public void add()
{
..................
..................
}
public void sub()
{
....................
...................
}
private Integer getValue()
{
return .........
}

public static void main(String a[])
{
new Sample();
}
}
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch! Please UseCodeTags when you post source code.

The constructor of a class is called automatically, but only when you create a new instance of that class.

Note that the main() method is a static method. That means it will be called without an instance of the Sample class. Java will not automatically create an instance of the class before calling the main() method. To understand what "static" means exactly, see: Understanding Instance and Class Members.

Inside the main() method, a new instance of class Sample is created using new Sample();. This will cause the constructor of class Sample to be called.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!