Java Object Reference Variable
In this chapter you will learn:
Description
Object reference variables act differently when an assignment takes place.
For example,
Box b1 = new Box();
Box b2 = b1;
After this fragment executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring.
A subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.
For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Example
Java Object Reference Variable
class Box {/*w ww . j ava2 s .co m*/
int width;
int height;
int depth;
}
public class Main {
public static void main(String args[]) {
Box myBox1 = new Box();
Box myBox2 = myBox1;
myBox1.width = 10;
myBox2.width = 20;
System.out.println("myBox1.width:" + myBox1.width);
System.out.println("myBox2.width:" + myBox2.width);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Java Object
Java Object Reference Variable
Java MethodsJava Method Return
Java Method Parameters
Java Class Constructors
Java Default Constructor
Java Constructor Parameters
Java this Keyword
Java static keyword
Java Method Overload
Java Constructors Overload
Java Method Argument Passing
Java Method Recursion
Java Nested Class
Java Anonymous Classes
Java Local Classes
Java Member Classes
Java Static Member Classes
Java Class Variables
Java main() Method
Java Class Inheritance
Java super keyword
Java Method Overriding
Java Constructor in hierarchy
Polymorphism
Java final keyword
Java Abstract class
Java Class Access Control
Java Package
Java Packages Import
Java Interface
Java Interface as data type
Java interface as build block
Java instanceof operator
Java Source Files