• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

constructor  RSS feed

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)
when a class is declared and we don't declare a constructor the compiler assigns the default constructor automatically and all the instatnce variables are declared to their default values.


public class Const {

private int i;
private int j;

public static void main ( String args[])

{
Const c = new Const();
c.i = c.i + 1;
System.out.println(c.i);
c.j = c.j + 1;
System.out.println(c.j);


}

}


output:

compile:
run:
1
1
BUILD SUCCESSFUL (total time: 0 seconds)
-------------------------------------------------------------------

now if we declare a constructor then


public class Const {

private int i;
private int j;

Const (){

j = j+1;

}

public static void main ( String args[])

{
Const c = new Const();
c.i = c.i + 1;
System.out.println(c.i);
c.j = c.j + 1;
System.out.println(c.j);


}

}


output

compile:
run:
1
2
BUILD SUCCESSFUL (total time: 0 seconds)
----------------------------------------------------------------


my question is since we declared a constructor the default constructor dosen't come into picture!!! so how did the value of i got initialized to the default value 0 even though we didn't initialized in our defined constructor.

[ August 31, 2007: Message edited by: deeksha mehra ]


[ August 31, 2007: Message edited by: deeksha mehra ]
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
When we create a class,all the instance variables will be intialized to zero. If explicitly intialize them in a constructor then only that variables will be affected and the rest of the variables will be initialized to zero.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!