Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Object Type and Reference Type

I was studying Polymorphism from "Head First Java" and came to this concept. Can anyone explain it please with an example?

Compiler checks the class of reference type -- not the Object type.

So what's the difference between Reference Type and Object Type?

like image 816
Sikander Avatar asked May 24 '13 07:05

Sikander


2 Answers

I don't think their use of "object type" and "reference type" is standardized, but here's my interpretation.

Consider this code:

Object o = new Integer(3);

The reference o is of type Object. The object that it references is of type Integer.

So the "reference type" would be Object and the "object type" would be Integer.

What makes this confusing is that there's the (standardized, official) term "reference type" that encapsulates types that can be referenced. In Java that includes all classes, enums, interfaces, arrays. It excludes only the primitive types (int, ...).

like image 118
Joachim Sauer Avatar answered Sep 21 '22 13:09

Joachim Sauer


What is meant by the terms is the following:

  • object type (in your book) = the actual runtime type of the referent
  • reference type (in your book) = the static type of the reference

Maybe some will find it easier to understand with these terms.

like image 31
Bruno Reis Avatar answered Sep 20 '22 13:09

Bruno Reis