lummers
lummers

Reputation: 779

What is meant by the word 'type' in relation to variables?

I am working my way through some starter Java using a book and one of the self-assessment questions is: "What is meant by the word 'type' in relation to variables in Java?"

Stumped me a little bit.

The book states that: “Reference type variables are declared in the same way as value type variables. First you give the name of the type (the class) and then the name of the variable.”

So my answer is: The word type, in relation to variables, means creating a name for the class which the variables can be used to reference instances of that class.

For example,

Toad frogger;

Would result in the type Toad which has a variable, frogger, which can reference instances of the Toad class, or type.

Is this correct? Thanks for anyone who can clear this up! :)

Upvotes: 3

Views: 242

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234797

You're pretty close. I'd phrase what you said like this:

Toad frogger;

results in a variable frogger which has a type reference to Toad. The variable holds a reference to an instance of the Toad class (or any object that is assignment compatible with Toad — see the Java Language Specification Sec. 5.2 ).

Chapter 4 of the Java Language Specification has a very nice explanation of the concept of type as used in Java.

Upvotes: 0

Mechkov
Mechkov

Reputation: 4324

Toad is the class/type and frogger is the reference name. The reference name holds/points to something that could be of type Toad or a subclass.

The reference name is also used to call different methods or to access the object, being pointed to by the reference.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500665

I would say it would be clearer to say that the variable frogger is of type Toad, which means:

  • The compile time type of the expression frogger is Toad - this is used for things like member resolution when you use frogger.foo(), and also if you do foo(frogger)
  • The value of frogger is always either null or a reference to an instance of Toad or a subclass. (So the value might be a reference to an instance of LesserSpottedToad, for example.)

Upvotes: 2

Related Questions