Constructors are used by the VM to configure newly instantiated objects. The constructor construct differs from regular methods in that there is no return type (because *we* don't call them, the JVM runtime does!), and they cannot be called from regular methods, but only by the "new" operator and from the first instruction in another constructor.
Example:
public class Dongle{
private int weight;
private Color color;
//default ctor
public Dongle(){
//use other ctor to configure default values
this(1, Color.WHITE);
}
public Dongle(Color c){
weight = 1;
color = c;
}
public Dongle(Color c, int wt){
weight = wt;
color = c;
}
}
If you do not provide at least one constructor, the compiler will insert a default constructor into the byte-code (not your source) to guarantee the "new" operator has something to use to configure your object. If it was in your code, it would look like this:
public MyClassName(){
super();
}
where "MyClassName" would be the name of your class, of course.
Notice the super call? The first instruction in a constructor is always a call to another constructor (super means the super class, this means this class). What happens is that the initialization runs immediately through the super classes all the way to java.lang.Object's constructor, executes, then returns back to the next constructor, etc. to ensure that your object and all it's inherited instance variables are initialized in the right order, with your constructor instructions having the final say, so to speak. If you do not explicitly use "super" or "this" as the first line, the compiler will put "super()", a call to the super class default constructor. Note that you will get a compiler error if the super class does NOT have a default constructor. That's your first clue that you need to explicitly specify which existing superclass constructor is to be used, by using "super(args...)".
It seems complex, but it all works to insure that your Java objects get instantiated correctly and in a deterministic way. Also note, it relieves you from having to include the boiler plate "plumbing" code that a Java object would need, since that is all encapsulated in the java.lang.Object class' constructor! We NEVER need to write it or even know it!
2007-03-05 07:51:52
·
answer #1
·
answered by vincentgl 5
·
0⤊
0⤋
The purpose of the constructor is to initialize the attributes of the class and to create a new instance of the class. I don't think that the JVM creates a constructor for a class if you don't create one. Classes that aren't declared as static will get flagged with an error and won't compile if they don't have at least a default constructor. You can make a default constructor which does nothing and accepts no parameters.
2007-03-04 17:39:50
·
answer #2
·
answered by rowancompsciguy 3
·
0⤊
1⤋