COMP 202 Lecture Notes - Lecture 11: Mutator Method, Static Variable
COMP 202: Foundations Of Programming
Lecture 11: Object-Oriented Programming
Keywords:
Static:
We can define an attribute/method to be static if we want it to be the same for every instance of the class.
A static attribute/method belongs to the whole class. A non-static attribute/method belongs only to an instance
of the class.
Static vs. Non-Static
Static
Non-Static
Associated with
Entire class (one per class)
Instance of class (one per
object/instance)
How to call (methods) from
outside of class
ClassName.MethodName()
Object.MethodName()
How to reference (data) from
outside of class
ClassName.VariableName
Object.VariableName
Can it access the non-static fields
belonging to this object?
No
Yes
String s = “apple”;
String t = “pear”;
int x = s.length();
double x = Math.PI;
int y = Integer.parseInt(“0”);
What is externally visible?:
We now have multiple files/classes, each with their own data and methods.
We must decide:
- What should be visible from OUTSIDE of the class?
- Should all methods be usable?
- Should all data be usable?
So far, all of the attributes and methods we have written have been public.
A public method or attribute can be accessed from outside of the class file in which it was written.
In contrast, an attribute or method with a private modifier cannot be accessed from outside the class file in
which it was written.
Private:
The method or variable that uses the private access-specifier, is only visible within the class.
The method or variable that uses the public access-specifier, is visible everywhere.
length() is a non-static method. It
belongs to a particular String
PI is a static variable. It belongs to all of
Math.
parseInt is a static method. It belongs to
the Integer class.
find more resources at oneclass.com
find more resources at oneclass.com
jc123 and 40170 others unlocked
100
COMP 202 Full Course Notes
Verified Note
100 documents
Document Summary
We can define an attribute/method to be static if we want it to be the same for every instance of the class. A static attribute/method belongs to the whole class. A non-static attribute/method belongs only to an instance of the class. String t = pear ; int x = s. length(); double x = math. pi; int y = integer. parseint( 0 ); We now have multiple files/classes, each with their own data and methods. So far, all of the attributes and methods we have written have been public. A public method or attribute can be accessed from outside of the class file in which it was written. In contrast, an attribute or method with a private modifier cannot be accessed from outside the class file in which it was written. The method or variable that uses the private access-specifier, is only visible within the class. The method or variable that uses the public access-specifier, is visible everywhere.