KEMBAR78
Lecture_4_Static_variables_and_Methods.pptx
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:
1.variable (also known as class variable)
2.method (also known as class method)
3.block
4.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
1. class Student {
2. int rollno;
3. String name;
4. static String college =“MCS";
5. Student ( int r, String n ) {
6. rollno = r;
7. name = n;
8. }
9. void display ( ){
System.out.println (rollno +" "+name+" "+college); }
10. public static void main (String args[ ]) {
11. Student s1 = new Student (111,“Omer");
12. Student s2 = new Student (222,“Hamza");
13. s1.display();
14. s2.display();
15. } }
6
Example 2: Static Variables
(Programof counter by Static variables)
1. class Counter2{
2. static int count=0; //will get memory only once and retain its value
3. Counter2( ){
4. count++;
5. System.out.println(count);
6. }
7. public static void main(String args[ ]){
8. Counter2 c1=new Counter2( );
9. Counter2 c2=new Counter2( );
10. Counter2 c3=new Counter2( );
11. }
12.}
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
o You can execute class methods even when no objects of a class
exist.
o 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.
• Static method can access static data member and can change the
value of it.
Restrictions for static method
1. The static method can not use non-static data member or call non-
static method directly.
2. this and super cannot be used in static context.
10
1. class Student {
2. int rollno;
3. String name;
4. static String college = “SEECS";
5. static void change( ) {
6. college = “MCS";
7. }
8. Student ( int r, String n){
9. rollno = r;
10. name = n; }
11. void display ( ) { System.out.println (rollno+" "+name+" "+college); }
12. public static void main (String args[ ]){
13. Student.change( ); // Static Method Call
14. Student s1 = new Student (111,“Omer");
15. Student s2 = new Student (222,“Hamza");
16. s1.display();
17. s2.display();
18. } }
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
Sample Messages
BankAccount anAcct = new BankAccount("Moss", 500.00);
anAcct.withdraw(50);
anAcct.deposit(120.00);
System.out.println(“Balance ="+ anAcct. getBalance() );
21
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
Example
public void print ( String temp ){
System.out.println("Name:" + name);
System.out.println("Address:" + address);
System.out.println("Age:" + age);
}
public void print (double eGrade, double mGrade, double sGrade)
System.out.println("Name:" + name);
System.out.println("Math Grade:" + mGrade);
System.out.println("English Grade:" + eGrade);
System.out.println("Science Grade:" + sGrade);
}
23
Example
public static void main( String[] args )
{
StudentRecord aRecord = new StudentRecord();
aRecord.setName(“Ahmed");
aRecord.setAddress(“Pakistan");
aRecord.setAge(15);
aRecord.setMathGrade(80);
aRecord.setEnglishGrade(95.5);
aRecord.setScienceGrade(100);
//overloaded methods
aRecord.print( aRecord.getName() );
aRecord.print( aRecord.getEnglishGrade(), aRecord.getMathGrade(),
aRecord.getScienceGrade());
}
24
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

Lecture_4_Static_variables_and_Methods.pptx

  • 1.
    Static Variables andMethods OBJECT-ORIENTED PROGRAMMING BESE 22
  • 2.
    Instance and Classvariables • 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
  • 3.
    Instance and Classvariables • 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
  • 4.
    Java static keyword Thestatic 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: 1.variable (also known as class variable) 2.method (also known as class method) 3.block 4.nested class 4
  • 5.
    Static Variable • Ifyou 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
  • 6.
    1. class Student{ 2. int rollno; 3. String name; 4. static String college =“MCS"; 5. Student ( int r, String n ) { 6. rollno = r; 7. name = n; 8. } 9. void display ( ){ System.out.println (rollno +" "+name+" "+college); } 10. public static void main (String args[ ]) { 11. Student s1 = new Student (111,“Omer"); 12. Student s2 = new Student (222,“Hamza"); 13. s1.display(); 14. s2.display(); 15. } } 6
  • 7.
    Example 2: StaticVariables (Programof counter by Static variables) 1. class Counter2{ 2. static int count=0; //will get memory only once and retain its value 3. Counter2( ){ 4. count++; 5. System.out.println(count); 6. } 7. public static void main(String args[ ]){ 8. Counter2 c1=new Counter2( ); 9. Counter2 c2=new Counter2( ); 10. Counter2 c3=new Counter2( ); 11. } 12.} 7
  • 8.
    Instance and ClassMethods • 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
  • 9.
    Static Methods • ClassMethods o You can execute class methods even when no objects of a class exist. o Like class variables, these are declared using the keyword static, so also called static methods 9
  • 10.
    Static Methods If youapply 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. • Static method can access static data member and can change the value of it. Restrictions for static method 1. The static method can not use non-static data member or call non- static method directly. 2. this and super cannot be used in static context. 10
  • 11.
    1. class Student{ 2. int rollno; 3. String name; 4. static String college = “SEECS"; 5. static void change( ) { 6. college = “MCS"; 7. } 8. Student ( int r, String n){ 9. rollno = r; 10. name = n; } 11. void display ( ) { System.out.println (rollno+" "+name+" "+college); } 12. public static void main (String args[ ]){ 13. Student.change( ); // Static Method Call 14. Student s1 = new Student (111,“Omer"); 15. Student s2 = new Student (222,“Hamza"); 16. s1.display(); 17. s2.display(); 18. } } 11
  • 12.
    Instance Variables public classStudentRecord { // 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
  • 13.
    Class (static) variables publicclass 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
  • 14.
    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
  • 15.
    public class StudentRecordExample { publicstatic 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
  • 16.
  • 17.
    Accessor (Getter) Method publicclass StudentRecord { private String name; public double getAverage() { double result = 0; result = (mathGrade + englishGrade + scienceGrade) / 3; return result; } } 17
  • 18.
    Mutator (Setter) Method publicclass StudentRecord { private String name; public void setName( String temp ) { name = temp; } } 18
  • 19.
    An Example class publicclass 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
  • 20.
    class BankAccount public StringgetID () { return ID; } public double getBalance () { return balance; } public String toString ( ) { return ID + " $" + balance; } } // End class BankAccount 20
  • 21.
    Sample Messages BankAccount anAcct= new BankAccount("Moss", 500.00); anAcct.withdraw(50); anAcct.deposit(120.00); System.out.println(“Balance ="+ anAcct. getBalance() ); 21
  • 22.
    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
  • 23.
    Example public void print( String temp ){ System.out.println("Name:" + name); System.out.println("Address:" + address); System.out.println("Age:" + age); } public void print (double eGrade, double mGrade, double sGrade) System.out.println("Name:" + name); System.out.println("Math Grade:" + mGrade); System.out.println("English Grade:" + eGrade); System.out.println("Science Grade:" + sGrade); } 23
  • 24.
    Example public static voidmain( String[] args ) { StudentRecord aRecord = new StudentRecord(); aRecord.setName(“Ahmed"); aRecord.setAddress(“Pakistan"); aRecord.setAge(15); aRecord.setMathGrade(80); aRecord.setEnglishGrade(95.5); aRecord.setScienceGrade(100); //overloaded methods aRecord.print( aRecord.getName() ); aRecord.print( aRecord.getEnglishGrade(), aRecord.getMathGrade(), aRecord.getScienceGrade()); } 24
  • 25.
    Output Output for thefirst 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