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

Why constructor is not called. ?

 
Ambika Jain
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some clues - think about why the main method is public and static. How would the JVM call your program ?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Sheriff
Posts: 48396
56
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic