Object vs Reference Flashcards
Describe in clear terms the difference between an object and a reference !
The difference between an object and a reference is that in java, an object can be accessed using different reference variables but regardless of the reference variable used to access the object, the object itself doesn’t change
What is a common characteristic of java.lang.Object in the context of Object vs Reference ?
Any object in java can be assigned to a reference variable of the type java.lang.Object since all java classes extend directly or indirectly java.lang.Object
Give the rules of Object vs Reference !
We can summarize this principle with the following two rules:
- The type of the object determines which properties exist within the object in memory.
- The type of the reference to the object determines which methods and variables are accessible to the Java program.
How to regain access to a property that exists in memory but can not be accessed through a given reference variable ?
If an object possesses members in memory that can not be accessed through a reference variable, in order to regain access to those members, you have to change that reference variable to another type that gives you access to those members
This can involve upcasting (assigning to a superclass or interface type) or downcasting (assigning to a subclass type).