• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

constructor

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
To do a great right, do a little wrong - shakepeare. twisted little ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic