Static Elements (variables and Functions)
What:
These are elements having a relatively longer life.
They reside in the class i.e. their copies are not created when an object is instantiated
Technically they are created on the heap whereas local variables and object level elements are created on the stack which is a relatively volatile memory inside RAM
Why:
They are used to share data among various objects of the same class
How:
Static elements may be accessed without instantiating an object of the class
Static elements may access only static elements while non-static elements may access both static and other non-static elements
e.g.
class A{
private int x;
private int count = 0;
public A(){
this(0);
}
public A(int t){
this.x=t;
count++;
}
public int getx(){return x;}
public void setx(int t){this.x=t;}
public int getCount(){
return count;
}
public String toString(){
return "Count: " + count + " Value: " + x;
}
}
What:
These are elements having a relatively longer life.
They reside in the class i.e. their copies are not created when an object is instantiated
Technically they are created on the heap whereas local variables and object level elements are created on the stack which is a relatively volatile memory inside RAM
Why:
They are used to share data among various objects of the same class
How:
Static elements may be accessed without instantiating an object of the class
Static elements may access only static elements while non-static elements may access both static and other non-static elements
e.g.
class A{
private int x;
private int count = 0;
public A(){
this(0);
}
public A(int t){
this.x=t;
count++;
}
public int getx(){return x;}
public void setx(int t){this.x=t;}
public int getCount(){
return count;
}
public String toString(){
return "Count: " + count + " Value: " + x;
}
}
No comments:
Post a Comment