PDA

Click to See Complete Forum and Search --> : Instantiating class


Magnus_Lei
Aug 28th, 2002, 10:57 AM
example
public class CountFilps {

/** Creates a new instance of CountFilps */
public CountFilps() {
}

}

This is a class that Sun One put in when i told it to do a new class. Why is it automatically creating an instance of CountFlips? I don't understand this. I am new to Java and i am taking a class that has just started at a local college but i have decided to read a head and i don't understand what they are talking about.

Why do you Instantiate?

CaptainPinko
Aug 28th, 2002, 11:37 AM
that doesn't create a new instance in it self it is the "constructor" (a method (aka sub) thats is called to set the initial state of an object). there is plenty out there on constructors so i'll just give a small example


to create a new instance of CountFlips:
(ignoring the import statement)

CountFlips bob_the_acrobat = new CountFlips ();



now when creating a new new instance of an object, the code in the constructor is run so if the constructor code looked like this:

public CountFlips () {
System.out.println ("CaptainPinko pinks again!");
}


then whenever you created a new instance of CountFlips you'd get a message in the console that said CaptainPinko pinks again!. You can also pass arguments to your constructor like a regular sub:


public CountFlips (String name) {
System.out.println (name + " is a suXorZ!");
}


you can also overload the constructor so that your code could look like


public CountFlips (String name) {
System.out.println (name + " is a suXorZ!");
}

public CountFlips () {
System.out.println ("CaptainPinko pinks again!");
}


also, if you are extending a class you can also do constructor-chaining (calling a constructor of a parent class) by put the first line in your construtcor as super () (the arguments of super depend on the constructor of the parent class you are trying to call)

these examples show you how to, but not the useful aspects of constructors, for those i suggest you look at the constructors of the Color class in your JavaDocs (yes, i know they mispelled it, well forgive them this once) i think its in the java.awt.graphics package.

Magnus_Lei
Aug 28th, 2002, 01:37 PM
Thank you Captainpinko. You helped me alot and i appreciate your willingness to help me.


Thanks

CaptainPinko
Aug 28th, 2002, 04:19 PM
no prob!:)