CS212-Object Oriented Programming: Static Variables and Methods
CS212-Object Oriented Programming: Static Variables and Methods
Lecture 06
Static Variables and Methods
class
class Circle
Circle {{ unlike the getArea method that
double
double radius;
radius; was invoked on the myclass object
MCS instance, the method pow invoked
Circle(double
Circle(double newRadius)
newRadius) {{ on class Math without creating an
radius
radius == newRadius;
newRadius; object of the class. this pow is a
}} static method. Similarly, PI is a
Classes and Objects
double
double getArea()
getArea() {{ static variable, since we got the
return
return Math.pow(radius,
Math.pow(radius, 2) Math.PI; value without instantiating an
2) ** Math.PI;
}} object of the Math class
}}
Circle
public
public class
class CircleDemo
CircleDemo {{ radius: double
public
public static
static void
void main(String[]
main(String[] args)
args) {{
Circle Circle(newRadius: double)
Circle myCircle
myCircle == new
new Circle(10.0);
Circle(10.0);
getArea(): double
Circle
Circle yourCircle
yourCircle == new
new Circle(25.0);
Circle(25.0);
Circle
Circle theirCircle
theirCircle == new
new Circle(125.0);
Circle(125.0); myCircle: Circle
radius: 10
System.out.printf(
System.out.printf(
"Radius:
"Radius: %.2f;
%.2f; Area:
Area: %.2f\n",
%.2f\n", yourCircle: Circle
myCircle.radius,
myCircle.radius,
radius: 25
myCircle.getArea()
myCircle.getArea()
);
);
theirCircle: Circle
}}
}} radius: 125
MCS
Instance vs. Class Variables
• Instance variable are • Class variables are
those variables that are associated with the class
associated with each object and is shared by all objects
uniquely. of the class.
• Each instance of the class • There is only one copy of
will have its own copy of each of these variables no
each of these variables. matter how many class
• Each object will have its objects are created.
own values for each • They exist even if no
instance variable that objects of class have been
differentiate one object from created.
the other of the same class • These variables are also
type. called static fields because
• Declared in the usual way we use the keyword static
and can have an initial when we declare them.
value specified.
MCS
Static Variables
• Class variables are also called static variables
because we use the keyword static when we
declare them.
– The static variable gets memory only once in class
area at the time of class loading*
• When & Why do we use Static Variables?
– to refer the common property of all objects (that is not
unique for each object)
• E.g. company name of employees, college name of
students..
• It makes the program memory efficient (saves memory)
– to keep count of certain events
• E.g. Number of objects created for a certain class
class Student {
int rollno;
MCS
String name;
static String college = "MCS";
Sta Student(int r, String n) {
rollno = r;
tic name = n;
Var }
void Display( ) {
iab System.out.printf("%d: %s (%s)\n",
les rollno, name, college);
: }
public static void main(String[] args) {
Ex Student s1 = new Student(111, "Omer");
am Student s2 = new Student(222, "Hamza");
s1.Display();
ple s2.Display();
1 }
}
MCS
Static Variables: Example 2
class Counter {
// will get memory only once
// and retain its value
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
}
}
MCS
Instance vs. Class Methods
• Instance methods • Class methods can
can only be executed be executed even
in relation to a when no objects of a
particular object. class exist.
• If no object exists, no • Like class variables,
instance method can these are declared
be executed. using the keyword
static, so also
called static methods.
MCS
Static Methods
• A static method belongs to the class rather
than object of a class.
• A static method can be invoked without the
need for creating an instance of a class.
• Static method can access static data members
and can change their value.
Restrictions for static method
1. The static method can not use non-static/
instance data members or call instance
methods directly.
2. this and super cannot be used in static
context.
class Student {
int rollno;
MCS String name;
static String college = "EME";
static void Change() {
college = "MCS";
Sta }
Student(int r, String n) {
tic rollno = r;
name = n;
Me }
tho void Display( ) {
System.out.printf("%d: %s (%s)\n",
ds: rollno, name, college);
}
Ex public static void main(String[] args) {
am Student.Change(); // Static Method Call
Student s1 = new Student(111, "Omer");
ple Student s2 = new Student(222, "Hamza");
s1.Display();
1 s2.Display();
}
}
class Circle {
/** The radius of this circle */
MCS double radius;
/** Number of Circle objects */
static int numberOfObjects = 0;
/** Construct a circle object */
Circle() {
Sta radius = 1.0;
tic }
numberOfObjects++;
instantiate
c1: Circle Memory
Circle radius: 1.0 1.0
radius: double numberOfObjects: 2
numberOfObjects: int 2
Circle() c2: Circle
Circle(newRadius: double) instantiate
getNumberOfObjects(): int radius: 5.0 5.0
getArea(): double numberOfObjects: 2
UML Notation:
Underline: static variables or methods
MCS
Java static Keyword
• The static keyword in java is used
mainly for memory management
• We can apply Java static keyword
with:-
1. Variable (a.k.a. class variable)
2. Method (a.k.a. class method)
3. Block
4. Nested Class
• The static keyword belongs to the class
rather than instance of the class
MCS
package yourPack;
import myPack.*;
class B {
public static void main(String[] args {
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
MCS
The public Access Modifier
• The public access modifier is accessible everywhere.
• It has the widest scope among all other modifiers.
• The class, data, or method is visible to any class in any
package.
package myPack;
public class A {
public void msg() { System.out.println("Hello"); }
}
package yourPack;
import myPack.*;
class B {
public static void main(String[] args {
A obj = new A();
obj.msg();
}
}
MCS
Summary of Access Modifiers
Outside
Access Within Within Package by Outside
Modifier Class Package subclass Package
Only
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes
Example of Data Field Encapsulation
MCS
Circle
–radius: double The radius of this circle.
–numberOfObjects: int The number of circle objects created.
+Circle() Constructs a default circle object.
+Circle(newRadius: double) Constructs a circle object with specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(newRadius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.
MCS
Immutable Objects and Classes
• If the contents of an object cannot be changed
once the object is created, the object is called an
immutable object and its class is called an
immutable class.
• If we delete the set method in the Circle class
in the preceding example, the class would be
immutable because radius is private and
cannot be changed without a set method.
• A class with all private data fields and without
mutators is not necessarily immutable.
MCS
Immutable Class
For a class to be class
class Circle
Circle {{
private
private double
double radius;
radius;
immutable, it must
mark all data fields public
public Circle(double
Circle(double r_in)
if(r_in
if(r_in << 0)
0)
r_in) {{