Anda di halaman 1dari 1

IT1908

STATIC METHODS AND FIELDS Output: 5


Explanation: There is only one (1) num variable since it is
Fundamentals static.
• A static variable or class variable is any field declared with
the static modifier; this tells the compiler that there is exactly Static versus Instance
one (1) copy of this variable in existence, regardless of how • An instance variable or method requires an object of its
many times the class has been instantiated. class to be created before it can be used or called.
• A static method belongs to the class rather than the object
Type Accessing Legal? How?
of a class.
o It can be invoked without creating an instance of a Static Another static Yes Using the class name
class. method method or variable
o It can access static members and change their Static An instance method No
values. method or variable
• To call a static method or variable, put the class name before Instance A static method or Yes Using the class name
the method or variable. method variable or reference variable
Example: Instance Another instance Yes Using a reference
class NumberClass { method method or variable variable
public static int num = 0;
public static void displayNumber() { Example of a static method calling an instance method:
System.out.print(num); public class NumberClass {
} public static int num = 0;
} public static void main(String[] args) {
public class NumberClassDemo { displayNumber(); //does not compile
public static void main(String[] args) { }
System.out.print(NumberClass.num); public void displayNumber() {
NumberClass.displayNumber(); System.out.print(num);
} }
} }
Output: 00 Example of a static method trying to access an instance variable:
• An instance variable can be used to call a static method or public class NumberClass {
update a static variable. int num = 0;
Example: public static void main(String[] args) {
public class NumberClassDemo { displayNumber();
public static int num = 0; }
public static void main(String[] args) { public static void displayNumber() {
NumberClass nc1 = new NumberClass(); System.out.print(num); //does not compile
NumberClass nc2 = new NumberClass(); }
nc1.num = 6; }
nc2.num = 5;
System.out.print(NumberClass.num); Reference:
} Oracle Docs (n.d.). Citing sources. Retrieved from
} https://docs.oracle.com/javase/tutorial/java/javaOO/index.html

02 Handout 1 *Property of STI


 student.feedback@sti.edu Page 1 of 1

Anda mungkin juga menyukai