Java:Logic behind variables
Class:-
Class is an skeleton of object in which methods are defined and variables are declared.Example:-
Class Demo
{
int a;
int b;
public void print(){
System.out.println("this is demo class");
}
}
Here Demo is class where a and b are declared as instance variable and print is method.
Object:-
An object is set of constructors and variables.Such type of variables are called instance variables.
Creating object of a class:-
In Java we can create a new instance of a class using 'new' tag. This tag loads the instance in heap and give the reference of that.
Example:-
Demo d= new Demo();
What is reference of object?:-
Reference are same as you can say as a address in memory from where the instance is start. But because of security reason Java maps these addresses to some other values generated by its Virtual machine JVM. These values are called OBJECT ID and combination of it with context id called reference of object.In our last example It is store in variable d.
So If I try to print the address of object using variable d like this:-
System.out.println(""+d);
I can get something like this: 11ac12b3@12373326.
Here the portion after '@' is object id and before @ is CONTEXT ID.
What is Context:-
Context of object is an area of memory where the class of object loads. Here STATIC variables also loads.
Instance variables:-
In any class variables which declared outside the methods and constructors are called 'Instance variable' except static variables.Its name is instance because It loads on memory at the time of loading of Instance on heap.Because they are the part of instance,they always load on heap section of memory.
It is part of instance so it remains on memory until instance destroy.Hence we can say that Its lifetime and scope is same as instance.
Example:-
Class NewDemo
{
public static void main(String args[]){
Demo d=new Demo();
d.a=1; //Initializing
d.b=2; //instance variables
}
}
No comments:
Post a Comment