• Post Reply Bookmark Topic Watch Topic
  • New Topic

initializing  RSS feed

tom brownlee
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 right...is 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
Posts: 3014
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1049
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya, everything Greg said.
So you might want to do something like this:

Depending on that the constructor for Jewel looks like that is.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!