I have a class like
public class fun{
abc(){//.some code.//}
}
and in some main
method there is code like
fun obj = new fun();
fun obj1 = obj;
Please help me explain object in main
how the access class.
I have a class like
public class fun{
abc(){//.some code.//}
}
and in some main
method there is code like
fun obj = new fun();
fun obj1 = obj;
Please help me explain object in main
how the access class.
In Java there are two different things:
1) Reference Variable
2) Object
Reference Variable: It is stored in stack they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also. It is a variable that points to some object in memory.
Object: Objects are stored in heap memory. It is an instance of class that is dynamically created.
Here in your code obj
and obj1
are reference variables. When you do fun obj=new fun()
, you are creating Object of fun class and obj points to that object in memory. And in next line when you call fun obj1=obj
, now the obj1
is also pointing to same object which is being pointed by obj.
So technically both are pointing to same memory on heap. obj == obj1
will be evaluated to true
.
Note : Reference and Object definition reference.
(Thanks to pshemo for this info) And reference and reference variable is not the same thing. Reference (at least in Java) is unique number assigned to each object which can be used to find it by JVM. Reference variable is variable of type which can store references (as their value).
You posted this code as what's in your main
method:
fun obj = new fun();
fun obj1 = obj;
The first line is doing a few things...
new fun();
is calling the constructor on class fun
(which separately you should use a capital "F" to follow standard Java naming conventions). This will create a new instance of the fun
class, so there will be one fun
object.
fun obj = ...
that is defining a variable named obj
which holds a reference to a fun
object. An alternative might be String s
which would define a variable s
that references a String
object. Also, after this line is done, obj
will point at the actual Java object that was created by calling new fun();
.
The second line:
creates a new variable - obj1
- that references a fun
object
points obj1
at the same underlying object that obj
points to
So in the end, you have one object – the thing created from new fun()
– and two variables that reference that same object.