File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes initializing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "initializing" Watch "initializing" New topic


tom brownlee

Joined: Aug 14, 2001
Posts: 28
how do i initialize a class reference?
what i mean is: for int its, int i = 0;
for String its, String s = "";
so to use a method from another class i would use, say (my problem code)

where the 'jewelInRoom' method is in the Jewel class.
everytime i compile it, it works but at runtime i get a problem where i haven't initialized 'currentJewel'. i presume if i initialize the currentJewel to a color(parimeter of Jewel) the code wont work. well at least it didnt when i did it. i tested it by printing out jewelInRoom and i got 'null' on the screen when i should of got the jewel color(more code needed to understand) i know theres more code to add to properly make this sound sane but am i doing it it because im initializing currentJewel to a color that i get 'null' on screen, or is there an initializing code to use to make this work? as with int i = 0; or String s = '';
Greg Charles

Joined: Oct 01, 2001
Posts: 2968

This is one of the first really tough concepts to get into your head when you begin with an object-oriented language like Java. There's a fundamental difference between primitives (like int and double) and Classes, like your Jewel.
When you say:
Casa miCasa;
you have created something called a reference, which can refer to an object of type Casa. However it doesn't currently refer to anything. No Casa has been created. You can make it refer to an already existing Casa object by saying:
miCasa = tuCasa;
In this case, there is still only one Casa, but both miCasa and tuCasa refer to it. On the other hand, you can construct a new Casa and have miCasa refer to that.
miCasa = new Casa();
Now, miCasa and tuCasa refer to two different Casas.
String, incidentally, is a bit of a hybrid. You could treat it like any other Class, like so:
String hint = new String("Casa is Spanish for house");
but the Java language provides special String literals, so you can just say:
String myString = "I hope I'm not confusing you!";
Very few classes have convenient literals like this, and none of the ones you define do, so you'll have to write:
Jewel myJewel = new Jewel();
or something similar, depending on the constructors defined in the Jewel class.
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Ya, everything Greg said.
So you might want to do something like this:

Depending on that the constructor for Jewel looks like that is.

Please ignore post, I have no idea what I am talking about.
I agree. Here's the link:
subject: initializing
It's not a secret anymore!