Static Variables and Methods in Object-Oriented Programming

Module 2 - Part 2
Static Keyword
O
v
e
r
v
i
e
w
Static Class Members discussed: 
Static Variables
Static Methods within static classes
Examples of commonly used Static methods
V
a
r
i
a
b
l
e
s
/
A
t
t
r
i
b
u
t
e
s
 
i
n
 
a
n
 
o
b
j
e
c
t
class
 Number {
 
int
 x;
 
public
 Number(
int
 x) {
   
this
.x=x;
 }
}
class
 Main {
 
public
 
static
 
void
 main(String[] args) {
   Number a = 
new
 Number(
5
);
   Number b = 
new
 Number(
8
);
 }
}
a
x=5
x=8
b
S
e
p
a
r
a
t
e
 
x
 
a
t
t
r
i
b
u
t
e
s
Notice how each object has its own 
x
attributes.
Changes to the 
x
 attribute in object 
a
will have no effect on changes to the 
x
attribute in object 
b
W
h
a
t
 
i
f
 
y
o
u
 
n
e
e
d
e
d
 
a
 
s
h
a
r
e
d
 
v
a
r
i
a
b
l
e
?
Imagine you write a set of classes to mimic a fast-
food restaurant.
You write a class called 
cookFrys
 and one called
cookBurgers
.  Then you have classes called
takeOrder
 and 
packOrder
When 
cookBurgers
 completes a burger where should
they put it?
One choice would be an array of Burgers in their object
But what if you have 3 
cookBurgers
 objects all cooking
simultaneously?
A 
packOrder
 object would have to look at the array in
each of the workers objects to see if they have a burger
B
e
t
t
e
r
 
S
o
l
u
t
i
o
n
Instead, perhaps it would be better if all the
cookBurger
 workers put their burgers in a shared
array.
Then the 
packOrder
 people only have to look in one
place.
But how to share a variable/attribute between
objects?
One option is to make the variable 
static
.
S
t
a
t
i
c
 
V
a
r
i
a
b
l
e
s
/
A
t
t
r
i
b
u
t
e
s
Previously, each instance/object had its own independent
set of variables
Static variables (a.k.a class variables) are shared among
all instances of a class
A variable become static by adding the reserved word
static
e . g. 
static int noOfCars =0;
A local variable cannot be static if the method is not static
Constants which are instance variables are often static
because just having one copy is good enough
Good for counting the number of instances
E
x
a
m
p
l
e
 
o
f
 
s
t
a
t
i
c
 
a
t
t
r
i
b
u
t
e
s
class
 Dog {
  
static
 
int
 dogCounter = 
0
; 
// Shared by all dogs
  
private
 
int
 dogID;  
// Each dog has its own copy
  Dog() {
    dogID = dogCounter++;
  }
}
Dog d1 = 
new
 Dog();  
// d1’s ID is 0, dogCounter is now 1
Dog d2 = 
new
 Dog();
// d2’s ID is 1, dogCounter is now 2
W
h
y
 
u
s
e
 
a
 
s
t
a
t
i
c
 
v
a
r
i
a
b
l
e
?
Probably the most common
example is when you need to count
how many objects of a given class
are created, or you need to number
those objects.
Think of KSU IDs. 
Each Student/Faculty/Staff is a
separate object
Thus each person needs
their own unique ID in their
object
However, somewhere you
must keep track of the last ID
you assigned.
This would be the static
variable in your class KSU
class KSU {
  public static int next_id=0;
  private int id;
  public KSU {
    id=next_id++;
  }
}
S
t
a
t
i
c
 
M
e
t
h
o
d
s
A Static method (A.K.A class method) is invoked
through a class name
An object is not instantiated
A method becomes static by adding the static
reserved word to the method header:
public 
static
 int carCount ()
The main method in Java & C# is static:
 public 
static
 void m/Main()
A static method can access only static variables and
local variables
S
t
a
t
i
c
 
M
e
t
h
o
d
 
E
x
a
m
p
l
e
class
 Dog {
  
static
 
int
 dogCounter = 
0
;
  
private
 int dogID;
  Dog() {
    dogID = dogCounter++;
  }
  
static
 
void
 allowed() {
    dogCounter *= 
2
;
  }
  
static
 
void
 notAllowed() { 
// Won’t compile
    dogID = 
10
;
  }
}
Dog d1 = new Dog();  
d1.allowed();
Dog.allowed();
Dog.notAllowed(); 
// Why doesn’t this work?
S
t
a
t
i
c
 
M
e
t
h
o
d
 
E
x
a
m
p
l
e
Ulike Java, C# only allows you to call static methods via the class.
You cannot call them via an object.
class
 Dog {
  
static
 
int
 dogCounter = 
0
;
  
private
 int dogID;
  Dog() {
    dogID = dogCounter++;
  }
  public 
static
 
void
 allowed() {
    dogCounter *= 
2
;
  }
}
//Main:
Dog d1 = new Dog();  
d1.allowed();  
//This is not permitted in C#, results in compile error
Dog.allowed();
A
d
d
i
n
g
 
m
e
t
h
o
d
s
 
t
o
 
y
o
u
r
 
m
a
i
n
 
c
l
a
s
s
You may have noticed that if you add a method to
your main class, you have to declare it static.
This is because the main method is static, so
everything it calls must be static.
S
t
a
t
i
c
 
V
a
r
i
a
b
l
e
s
 
-
 
E
x
a
m
p
l
e
public class factoryWorker {
  private String name;  
  private int empId;
  private 
static
 int nextId = 1;
  public int getId() {
    return empId;
  }
  public void setId() {
    empId = nextId; // set id to next available id
    nextId++;
  }
  public static int getNextId() {
    return nextId; // returns static field
  } 
}
public class StaticTest {
  public static void main(String[] args) {
    factoryWorker fw = new factoryWorker();
    int n = factoryWorker.getNextId();       
    System.out.println("Next available id=" +
n);
  }
}
S
t
a
t
i
c
 
V
a
r
i
a
b
l
e
s
 
-
 
E
x
a
m
p
l
e
public class factoryWorker {
  private string name;  
  private int empId;
  private 
static
 int nextId = 1;
  public int getId() {
    return empId;
  }
  public void setId() {
    empId = nextId; // set id to next available
id
    nextId++;
  }
  public static int getNextId() {
    return nextId; // returns static field
  } 
}
public class Program {
  public static void Main(string[] args) {
    factoryWorker fw = new
factoryWorker();
    int n = factoryWorker.getNextId();       
    Console.WriteLine("Next available id=" +
n);
  }
}
C
o
m
m
o
n
l
y
 
u
s
e
d
 
S
t
a
t
i
c
 
M
e
t
h
o
d
Math Class
abs ()
 
min()
max()
sqrt()
Integer Class
parseInt()
Double Class
parseDouble()
S
t
a
t
i
c
 
C
l
a
s
s
e
s
Not critical to understand at this point.  Static classes
work differently in C# and Java.
C#
Static classes can be declared anywhere.   They
cannot be instantiated
Java
It is possible, but not common (especially in this
class) to create classes inside of classes.
When you do that, you can declare the inner
class static.
It can only access static members of the outer
class
This is not something we’ll test you on here, we just
want you to be aware it exists.
S
u
m
m
a
r
y
Static Methods can be accessed using a
class name
Static variables are common across all
instances of a class
The reserved word 
static
 is used to identify
a variable or method as static 
Slide Note
Embed
Share

Explore the concept of static variables and methods in object-oriented programming. Learn how static attributes are shared among all instances of a class, enabling a single copy of the variable to be used across objects. Discover examples and illustrations demonstrating the use of static variables for efficient data sharing in classes.

  • Static Variables
  • Object-Oriented Programming
  • Shared Attributes
  • Static Methods
  • Class Instances

Uploaded on Oct 01, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Module 2 - Part 2 Static Keyword

  2. Overview Static Class Members discussed: Static Variables Static Methods within static classes Examples of commonly used Static methods

  3. Variables/Attributes in an object class Number { int x; a b public Number(int x) { this.x=x; } } x=5 x=8 class Main { public static void main(String[] args) { Number a = new Number(5); Number b = new Number(8); } }

  4. Separate x attributes Notice how each object has its own x attributes. Changes to the x attribute in object a will have no effect on changes to the x attribute in object b

  5. What if you needed a shared variable? Imagine you write a set of classes to mimic a fast- food restaurant. You write a class called cookFrys and one called cookBurgers. Then you have classes called takeOrder and packOrder When cookBurgers completes a burger where should they put it? One choice would be an array of Burgers in their object But what if you have 3 cookBurgers objects all cooking simultaneously? A packOrder object would have to look at the array in each of the workers objects to see if they have a burger

  6. Better Solution Instead, perhaps it would be better if all the cookBurger workers put their burgers in a shared array. Then the packOrder people only have to look in one place. But how to share a variable/attribute between objects? One option is to make the variable static.

  7. Static Variables/Attributes Previously, each instance/object had its own independent set of variables Static variables (a.k.a class variables) are shared among all instances of a class A variable become static by adding the reserved word static e . g. static int noOfCars =0; A local variable cannot be static if the method is not static Constants which are instance variables are often static because just having one copy is good enough Good for counting the number of instances

  8. Example of static attributes class Dog { static int dogCounter = 0; // Shared by all dogs private int dogID; // Each dog has its own copy Dog() { dogID = dogCounter++; } } Dog d1 = new Dog(); // d1 s ID is 0, dogCounter is now 1 Dog d2 = new Dog(); // d2 s ID is 1, dogCounter is now 2

  9. Why use a static variable? Probably the most common example is when you need to count how many objects of a given class are created, or you need to number those objects. Think of KSU IDs. Each Student/Faculty/Staff is a separate object Thus each person needs their own unique ID in their object However, somewhere you must keep track of the last ID you assigned. This would be the static variable in your class KSU class KSU { public static int next_id=0; private int id; public KSU { id=next_id++; } }

  10. Static Methods A Static method (A.K.A class method) is invoked through a class name An object is not instantiated A method becomes static by adding the static reserved word to the method header: public static int carCount () The main method in Java & C# is static: public static void m/Main() A static method can access only static variables and local variables

  11. Static Method Example class Dog { static int dogCounter = 0; private int dogID; Dog() { dogID = dogCounter++; } static void allowed() { dogCounter *= 2; } static void notAllowed() { // Won t compile dogID = 10; } } Dog d1 = new Dog(); d1.allowed(); Dog.allowed(); Dog.notAllowed(); // Why doesn t this work?

  12. Static Method Example Ulike Java, C# only allows you to call static methods via the class. You cannot call them via an object. class Dog { static int dogCounter = 0; private int dogID; Dog() { dogID = dogCounter++; } public static void allowed() { dogCounter *= 2; } } //Main: Dog d1 = new Dog(); d1.allowed(); //This is not permitted in C#, results in compile error Dog.allowed();

  13. Adding methods to your main class You may have noticed that if you add a method to your main class, you have to declare it static. This is because the main method is static, so everything it calls must be static.

  14. Static Variables - Example public class factoryWorker { public class StaticTest { public static void main(String[] args) { factoryWorker fw = new factoryWorker(); private String name; private int empId; private static int nextId = 1; int n = factoryWorker.getNextId(); System.out.println("Next available id=" + n); } } public int getId() { return empId; } public void setId() { empId = nextId; // set id to next available id nextId++; } public static int getNextId() { return nextId; // returns static field } }

  15. Static Variables - Example public class factoryWorker { public class Program { public static void Main(string[] args) { factoryWorker fw = new factoryWorker(); private string name; private int empId; private static int nextId = 1; public int getId() { return empId; } int n = factoryWorker.getNextId(); Console.WriteLine("Next available id=" + n); } } public void setId() { empId = nextId; // set id to next available id nextId++; } public static int getNextId() { return nextId; // returns static field } }

  16. Commonly used Static Method Math Class abs () min() max() sqrt() Integer Class parseInt() Double Class parseDouble()

  17. Static Classes Not critical to understand at this point. Static classes work differently in C# and Java. C# Static classes can be declared anywhere. They cannot be instantiated Java It is possible, but not common (especially in this class) to create classes inside of classes. When you do that, you can declare the inner class static. It can only access static members of the outer class This is not something we ll test you on here, we just want you to be aware it exists.

  18. Summary Static Methods can be accessed using a class name Static variables are common across all instances of a class The reserved word static is used to identify a variable or method as static

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#