03 OOP ClassesAndObjects Continued
03 OOP ClassesAndObjects Continued
03 OOP ClassesAndObjects Continued
July 2012
1
Class
Object
More on class
Enum types
More aspects of classes that depend on using object references and the
dot operator:
Access control
Any method declared void does not return a value. It does not need to
contain a return statement but we can use return; to break a control flow
block and exit the method.
Any method that is not declared void must contain a return statement with
a corresponding return value: return value;
4
For members, there are two additional access modifiers: private and
protected.
protected: the member can only be accessed within its own package (as
with package-private) and by a subclass of its class in another package.
9
Use the most restrictive access level that makes sense for a particular
member. Use private unless you have a good reason not to.
10
Class variables:
When a number of objects are created from the same class blueprint, they each have
their own distinct copies of instance variables.
Each Bicycle object has 3 instance variables speed, gear, cadence, stored in different
memory locations.
Sometimes, you want to have variables that are common to all objects. You do that
with the static modifier.
Fields that have static modifier in their declaration are called static fields or class
variables. They are associated with the class rather than with any objects--fixed
location in the memory.
11
We need to keep track of how many // add a class variable for the
Bicycle objects that have been // number of Bicycle objects instantiated
created so that we know what ID to private static int numberOfBicycles = 0;
// ...
assign to the next one.
}
The final modifier indicates that the value of this field cannot
change.
static final double PI = 3.141592653589793;
static final int MAX_VALUE = 1000;
14
Exercise 3. Write a small program to test your deck and card classes.
Non-static nested classes (inner classes) have access to other members of the
enclosing class, even if they are declared private.
Static nested classes do not have access to other members of the enclosing
class.
A way of logically grouping classes that are only used in one place.
It increases encapsulation.
17
Like static class methods, a static nested class cannot refer directly
to instance variables or methods defined in its enclosing class. It can
use them only through an object reference.
18
19
Class
Object
More on class
Enum types
21
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
Mondays are bad.
System.out.println("Weekends are best."); Midweek days are so-so.
break; Fridays are better.
default: Weekends are best.
System.out.println("Midweek days are so-so."); Weekends are best.
break;
}
}
// ...
}
22
The enum class body can include methods and other fields.
23
25