0% found this document useful (0 votes)
13 views

Lect 6

ghhgg

Uploaded by

zd64811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lect 6

ghhgg

Uploaded by

zd64811
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

STATIC MEMBERS AND

METHODS
Static Members
 Java supports definition of global methods and variables that
can be accessed without creating objects of a class. Such
members are called Static members.
 Define a variable by marking with the static keyword .
 This feature is useful when we want to create a variable
common to all instances of a class.
 One of the most common example is to have a variable that
could keep a count of how many objects of a class have been
created.
 Note: Java creates only one copy for a static variable which
can be used even if the class is never instantiated.

2
Static Variables
 Define using static:

public class Circle {


// class variable, one for the Circle class, how many circles
public static int numCircles;

//instance variables,one for each instance of a Circle


public double x,y,r;
// Constructors...
}

 Access with the class name (ClassName.StatVarName):

nCircles = Circle.numCircles;
3
Static Variables - Example
 Using static variables:
public class Circle {
// class variable, one for the Circle class, how many circles
public static int numCircles = 0;
private double x,y,r;

// Constructors...
Circle (){
numCircles++;}
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++; }
CalculateCircumference()
Get and Set for all..
4
}
Class Variables - Example
 Using static variables:

public class CircleRunner{

public static void main(String args[]){


Circle circleA = new Circle( 10, 12, 20); // numCircles = 1
Circle circleB = new Circle(); // numCircles = 2
S.O.P ( Circle.numCircle);
}
}
circleA = new Circle(10, 12, 20) circleB = new Circle(0, 0, 0)

numCircles
5
Non-static Vs Static Variables

 Non-static variables : One copy per object. Every


object has its own instance variable.
 E.g. x, y, r (centre and radius in the circle)

 Static variables : One copy per class.


 E.g. numCircles (total number of circle objects created)

6
Important Points
 Use a static variable when all objects of a class must
use the same copy of the variable.
 Static variables have class scope. We can access a
class’s public static members through a reference to
any object of the class, or by qualifying the member
name with the class name and a dot (.)
 A class’s private static class members can be
accessed by client code only through methods of the
class.
Static Methods
 A class can have methods that are defined as static
(e.g., main method).
 Static methods can be accessed without using objects.
Also, there is NO need to create objects.
 They are prefixed with keyword “static”
 Static methods are generally used to group related
library functions that don’t depend on data members
of its class. For example, Math library functions.

8
ht ©
201
2
Pear
son
Add
The Math Class
ison
-
Wesl
ey.
 The Math class provides a number of standard
All
right
mathematical methods
s  It is found in the java.lang package, so it does not
rese
rved
require an import statement
.  All of its methods and data are static, therefore they are
invoked with the class name Math instead of a calling
object
 The Math class has two predefined constants, E (e, the base
of the natural logarithm system) and PI (, 3.1415 . . .)
area = Math.PI * radius * radius;

5-9
ht ©
201
2
Pear
Some Methods in the Class Math
son
Add (Part 1 of 5)
ison
-
Wesl
ey.
All
right
s
rese
rved
.

5-10
ht ©
201
2
Pear
Some Methods in the Class Math
son
Add (Part 2 of 5)
ison
-
Wesl
ey.
All
right
s
rese
rved
.

5-11
ht ©
201
2
Pear
Some Methods in the Class Math
son
Add (Part 3 of 5)
ison
-
Wesl
ey.
All
right
s
rese
rved
.

5-12
ht ©
201
2
Pear
Some Methods in the Class Math
son
Add (Part 4 of 5)
ison
-
Wesl
ey.
All
right
s
rese
rved
.

5-13
ht ©
201
2
Pear
Some Methods in the Class Math
son
Add (Part 5 of 5)
ison
-
Wesl
ey.
All
right
s
rese
rved
.

5-14
Comparator class with Static methods
// Comparator.java: A class with static data items comparision methods

class Comparator {
public static int max(int a, int b)
{
if( a > b)
return a;
else
return b;
}

public static String max(String a, String b)


{ Directly accessed using ClassName (NO Objects)
if( a.compareTo (b) > 0)
return a;
else
return b;
}
}
15
class MyClass {
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";

int a = 10;
int b = 20;

System.out.println(Comparator.max(a, b)); // which number is big


System.out.println(Comparator.max(s1, s2)); // which city is big
System.out.println(Comparator.max(s1, s3)); // which city is big
}
}
Static methods restrictions
 They can only call other static methods.
 They can only access static data.
 They cannot refer to “this” or “super” (more later) in
anyway.

17
 A static method cannot access non-static class
members, because a static method can be called
even when no objects of the class have been
instantiated.
 For the same reason, the this reference cannot be
used in a static method. The this reference must
refer to a specific object of the class, and when a
static method is called, there might not be any
objects of its class in memory.
Example – static data and methods
 Create a SavingsAccount class.
 Use a static data member annualInterestRate to store the
annual interest rate.
 The class contains a private data member savingsBalance
indicating the balance of account.
 Provide member function calculateMonthlyInterest that
calculates the monthly interest by multiplying the balance by
annualInterestRate divided by 12; this interest should be
added to savingsBalance.
 Provide a static member function modifyInterestRate that sets
the static annualInterestRate to a new value.
 Write a driver program to test class SavingsAccount.
Instantiate two different objects of class
SavingsAccount, saver1 and saver2, with balances of
$2000.00 and $3000.00, respectively.
 Set the annualInterestRate to 3 percent.
 Then calculate the monthly interest and print the new
balances for each of the savers.
 Then set the annualInterestRate to 4 percent, calculate
the next month's interest and print the new balances
for each of the savers.
Example - Calculator
 Create a class TwoDigitCalculator which allows user
to perform addition, subtraction, multiplication and
division on 2 digits.

 Analyse the data members and methods of this


class and implement
END

You might also like