• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
It looks like it's time for me to write you a reality check! Or maybe a tiny ad!
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic