Java Referencing vs creating instance
I am relatively new to Java, I want to understand the difference b/w referencing and instantiating.
I know if I have a class Bike and at some point use Bike bk = new Bike(); that would be creating an instance. But how about creating a reference? what does that mean?
thanks.
Re: Java Referencing vs creating instance
In your example bk is your reference. It references an object (Bike) (thats not 100% correct - bk is more a variable that saves the reference, but for understanding its ok i think :))
Re: Java Referencing vs creating instance
Nope, bk is a reference, the value of which is the location of the object created by 'new Bike()'.
Re: Java Referencing vs creating instance
If I point (reference) an already existing bike I'm not creating a bike; if I create a bike and then point at it I'm effectively protecting the bike against the evil garbage collector; e.g.
Code:
Bike a= new Bike(); // create a bike and point at it
Bike b= a; // point to an existing bike
a= null; // b still points at the bike
b= null; // now the bike can be collected
kind regards,
Jos
Re: Java Referencing vs creating instance
Thanks guys.
Quote:
Originally Posted by
Tolls
Nope, bk is a reference, the value of which is the location of the object created by 'new Bike()'.
I thought bk is an instance of Bike. If bk is a reference of bike, does that mean I can use them interchangeably?
Re: Java Referencing vs creating instance
The non-primitive variables we use in code are references to objects on the heap.
So 'bk' is a reference to the Bike object created by 'new Bike()'.
In the same way that:
The variable 'x' is an int primitive.
Re: Java Referencing vs creating instance
I understand. Then what's an instance?
Re: Java Referencing vs creating instance
Quote:
Originally Posted by
garnaout
I understand. Then what's an instance?
Anything you create with the 'new' operator is an instance of some class; in your example that Bike is an instance of your Bike class.
kind regards,
Jos
Re: Java Referencing vs creating instance