Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor

 
rahul mehra
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 ]
 
ShivaKumar Singani
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