• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why constructor is not called. ?

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When we call the "public static void main(String args[]) " method, why is the constructor not called. Is it not initializing the class.

When I execute this class: It does intialize the variable i and the static block. Why is the constructor not being called ? Why does constructor get called only when we create an instance using "new". In the program below is "Allgo" object not getting instantiated when the main() is getting called ?

public class Allgo {
static int i=6 ;
static {
System.out.println("--static--"+i);
}

Allgo(){
System.out.println("--const--"+i);
}
public static void main(String args[])
{
}

Thanks in advance
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Some clues - think about why the main method is public and static. How would the JVM call your program ?
 
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
Make sure you understand the difference between an object and a class.

A class is a "blueprint" which is used to make objects. An object is an instance of a class. A constructor does not initialize a class. It initializes an object.

Do you know exactly what static means? It means that something is class-wide; for example, if you have a static member variable, then there is just one variable which is shared by all objects of that class (versus a non-static member variable, of which there is a copy for each object of the class).

Have a look at this part of The Java Tutorial: Understanding Instance and Class Members
 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A question which may be related came up on these fora about a week ago, here. See whether it helps you at all.

CR
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic