Static Variables and Methods Object-Oriented programming BESE 22
Instance and Class variables Instance variable are those variables that are associated with each object uniquely. Each instance of the class will have its own copy of each of these variables . Each object will have its own values for each instance variables that differentiate one object from the other of the same class type. Declared in the usual way and can have an initial value specified. 2
Instance and Class variables Class variables are associated with the class and is shared by all objects of the class. There is only one copy of each of these variables no matter how many class objects are created. They exist even if no objects of class have been created. These variables are also called static fields because we use the keyword static when we declare them. 3
Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: variable (also known as class variable) method (also known as class method) block nested class 4
Static Variable If you declare any variable as static, it is known static variable. The static variable can be used 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 etc. The static variable gets memory only once in class area at the time of class loading. Advantage of Static Variable It makes your program memory efficient (i.e. it saves memory). 5
class Student { int rollno ; String name; static String college =“MCS"; Student ( int r , String n ) { rollno = r; name = n; } void display ( ){ System.out.println ( rollno +" "+name+" "+college ); } public static void main ( String args [ ]) { Student s1 = new Student (111,“Omer"); Student s2 = new Student (222,“Hamza"); s1.display (); s2.display (); } } 6
Example 2: Static Variables ( Program of counter by Static variables ) class Counter2{ static int count=0 ; // will get memory only once and retain its value Counter2( ){ count ++; System.out.println (count ); } public static void main(String args [ ]){ Counter2 c1=new Counter2 ( ); Counter2 c2=new Counter2 ( ); Counter2 c3=new Counter2 ( ); } } 7
Instance and Class Methods Instance Methods These methods can only be executed in relation to a particular object If no object exists, no instance method can be executed 8
Static Methods Class Methods You can execute class methods even when no objects of a class exist. Like class variables, these are declared using the keyword static, so also called static methods 9
Static Methods If you apply static keyword with any method, it is known as static method . 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. S tatic method can access static data member and can change the value of it. Restrictions for static method The static method can not use non-static data member or call non-static method directly. this and super cannot be used in static context. 10
class Student { int rollno ; String name; static String college = “SEECS"; static void change( ) { college = “MCS"; } Student ( int r, String n){ rollno = r; name = n; } void display ( ) { System.out.println ( rollno +" "+name+" "+college); } public static void main ( String args [ ]){ Student.change ( ); // Static Method Call Student s1 = new Student (111,“Omer"); Student s2 = new Student (222,“Hamza"); s1.display(); s2.display(); } } 11
Instance Variables public class StudentRecord { // Instance variables private String name; private int age; private double mathGrade ; private double englishGrade ; private double average; //we'll add more code here later } Declare instance variables as private so that only class methods can access them directly. 12
Class (static) variables public class StudentRecord { //static variables private static int studentCount; //we'll add more code here later } – we use the keyword static to indicate that a variable is a static variable. 13
Example public class StudentRecord { // Instance variables private String name; private String address; private int age; private double mathGrade ; private double englishGrade ; private double scienceGrade ; private double average; // Static variables private static int studentCount; StudentRecord () { studentCount ++; } public String getName () { return name; } public void setName ( String temp ) { name = temp; } public double getAverage () { double result = 0; result =( mathGrade+englishGrade+scienceGrade )/3; return result; } public static int getStudentCount () { return studentCount; } 14
public class StudentRecordExample { public static void main( String[] args ){ //create three objects for Student record StudentRecord aRecord = new StudentRecord(); StudentRecord bRecord = new StudentRecord(); StudentRecord cRecord = new StudentRecord (); //set the name of the students aRecord.setName (“ Atif "); bRecord.setName (“Saad"); cRecord.setName (“MCS"); //print name System.out.println ( aRecord.getName () ); //print number of students System.out.println ("Count="+ StudentRecord.getStudentCount ()); } } 15
Output Atif Count=3 16
Accessor (Getter) Method public class StudentRecord { private String name; public double getAverage () { double result = 0; result = ( mathGrade + englishGrade + scienceGrade ) / 3; return result; } } 17
Mutator (Setter) Method public class StudentRecord { private String name; public void setName ( String temp ) { name = temp; } } 18
An Example class public class BankAccount { private String ID; private double balance; public BankAccount (String initID , double initBalance ) { ID = initID ; balance = initBalance ; } // Credit this account by depositAmount public void deposit (double depositAmount ) { balance = balance + depositAmount ; } // Debit this account by withdrawalAmount public void withdraw (double withdrawalAmount ) { balance = balance - withdrawalAmount ; } 19
class BankAccount public String getID () { return ID; } public double getBalance () { return balance; } public String toString ( ) { return ID + " $" + balance; } } // End class BankAccount 20
Overloading Methods Method overloading allows a method with the same name but different parameters , to have different implementations and return values of different types can be used when the same operation has different implementations. Always remember that overloaded methods have the following properties: the same method name different parameters or different number of parameters return types can be different or same 22
Output Output for the first call to print, Name: Ahmed Address: Pakistan Age:15 Output for the second call to print, Name: Ahmed Math Grade:80.0 English Grade:95.5 Science Grade:100.0 25