Computer Science 15-100 (APEA Section E), Summer 2008
Class Notes: Writing Classes
Logistics
- Schedule
- Friday: hw7 + quiz7
- Monday: hw8 + quiz8
- Wednesday: Final Exam
- Next Friday: Term Projects + All Bonus Projects
- Speaking of Bonus Projects...
- Reading:
- Ch 4: Writing Classes
- Ch 7.5: Varargs (Variable-Length Parameter Lists)
Topic Outline:
- Varargs: Variable-length arguments as arrays
public static void main(String[] args) throws Exception {
System.out.println(max(1,3,5,7,6,4,2));
}
public static int max(int... a) {
if (a.length == 0) return 0;
int max = a[0];
for (int i=1; i<a.length; i++) max = Math.max(max,a[i]);
return max;
}
- Visibility Modifiers
- public: visible to everyone
- protected: only visible within the given package or within
subclasses
- default: only visible within the given package
- private: only visible within the given class
- Instance Variables
- Non-static
- Require some object reference to access (hence, "instance"
variables)
- Should be private (maybe default?)
- Can be initialized outside of a constructor
- Initialized before constructor is called
- Scope
- Visible from all instance methods (but not static methods!)
- Shadowing
- Using this.foo to escape shadowing
- Accessors and Mutators
- Accessor: getFoo
- Mutator: setFoo, clearFoo, incrementFoo, etc...
- For booleans: isProperty, setProperty
- Constructors
- Default Constructor: No args, get this for free unless
you implement a constructor
- Invoking "super" constructor
- Invoking "this" constructor
- The toString method
- Every class gets a default toString method
- Can "override" this with your own
- Must have exactly this signature, visibility, and return
type:
public String toString()
- A Class's API (Application Programming Interface)
- All your public methods, and only your public methods
- What methods should be public in the Rational class?
- Encapsulation, Data Hiding, Self-Governing:
Control access to, and changing of, object properties
which is roughly equivalent to:
Expose public interface without reference to private
implementation
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem