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

Lecture-7 Static Data and Methods

Uploaded by

Quraisha Azam
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)
17 views

Lecture-7 Static Data and Methods

Uploaded by

Quraisha Azam
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/ 17

Lecture – 7

Static Data and Methods


Java static keyword
• 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.

4-2
Java static keyword
The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class

4-3
Understanding the Problem without static
Suppose there are 500 students in my college, now all class Student{
instance data members will get memory each time when int rollno;
the object is created. All students have its unique rollno String name;
and name, so instance data member is good in such case. String college="ITS";
Here, "college" refers to the common property of }
all objects. If we make it static, this field will get the
memory only once.

• static is used for a constant variable or a method that is same for


every instance of a class.

4-4
class Student{
int rollno;//instance variable Example
String name;
static String college ="CUI";//static variable Static
Student(int r, String n){
rollno = r;
name = n;
} 111 Ahmad CUI
Student(){} 222 Zainab CUI
//method to display the values
void display (){
System.out.println(rollno+" "+name+" "+college);
}
}
public class StudentTest{
public static void main(String[] args){
Student s1 = new Student(111,"Ahmad");
Student s2 = new Student(222,"Zainab");
s1.display();
s2.display();

}
} 4-5
Defining Class Variable as Static
public class Circle{
public static int numOfCircles; public class CircleTest{
public static void main(String[] args){
private int radius; Circle c1 = new Circle();
private final double PI = 3.14; c1.setRadius(2);
public Circle(){ System.out.println("C1 Area: "+ c1.getArea());
radius = 0; Circle c2 = new Circle(4);
System.out.println("C2 Area: "+ c2.getArea());
numOfCircles++; System.out.println("So far we have "+
} Circle.numOfCircles+" circle objects");
public void setRadius(int r){
}
this.radius = r; }
}
public Circle(int radius){ C1 = new Circle() C2 = new Circle(2)
this.radius = radius;
numOfCircles++;
}
public double getArea(){
return radius * radius * PI;
} numOfCircles

} 4-6
Non-static Vs Static Variables

• Non-static variables : One copy per object. Every object has its
own instance variable.
– E.g. radius in the circle

• Static variables : One copy per class.


– E.g. numOfCircles (total number of circle objects created)

7
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(c1.numOfCircles), or with the class name and a dot
(.)(Circle.numOfCircles)

• A class’s private static class members can be accessed by client


code only through methods of the class.
Static Methods
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an
instance of a class.
• A static method can access static data member and can change the
value of it.

9
class Student{
int rollno;//instance variable
String name;
private static String college ="CUI";//static variable
Student(int r, String n){
rollno = r;
name = n;
}
Student(){}
void display (){ 111 Ahmad QAU
System.out.println(rollno+" "+name+" "+college); 222 Zainab QAU
}
public static void changeUni(String uni){
university = uni;
}

public class StudentTest{


public static void main(String[] args){
Student s1 = new Student(111,"Ahmad");
Student s2 = new Student(222,"Zainab");
Student.changeUni("QAU");
s1.display();
s2.display();

}
}
4-10
Important Points

•They can only call other static methods.


•They can only access static data.
•They cannot refer to “this” or “super” (more later) in anyway.
4-11
Example

4-12
Example

Independent of any specific


instance.
4-13
Example
• Suppose that the class F is defined in (a). Let f be an instance of
F. Which of the statements in (b) are correct?

4-14
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.
Example – static data and methods
• 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

You might also like