wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor" Watch "constructor" New topic
Author

constructor

rahul mehra
Ranch Hand

Joined: Aug 20, 2007
Posts: 33
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 ]

Thanks
ShivaKumar Singani
Greenhorn

Joined: Aug 16, 2007
Posts: 7
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.
 
wood burning stoves
 
subject: constructor