Win a copy of Pragmatic AI this week in the Artificial Intelligence forum!
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!