Object-Oriented Programming
Lecture 3: Classes and Objects
Dr. L H!ng Ph"#ng -- Department of Mathematics, Mechanics and Informatics, VNUH
July 2012
1
Tuesday, July 31, 12
Content
Class
Object
More on class
Enum types
Package and the class path
Documentation comments for class
Number and String
2
Tuesday, July 31, 12
More on classes
More aspects of classes that depend on using object references and the
dot operator:
Returning values from methods
The this keyword
Class vs. instance members
Access control
Tuesday, July 31, 12
Returning a value from a method
A method returns to the code that invoke it when it
completes all the statement in the method,
reaches a return statement, or
throws an exception (covered later),
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
Tuesday, July 31, 12
Returning a value from a method
The getArea method return a primitive type (int):
public int getArea() {
return width * height;
}
A method can also return a reference type. In a program to manipulate
Bicycle objects, we might have a method like this:
public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike,
Environment env) {
Bicycle fastest;
// code to calculate which bike is
// faster, given each bike's gear
// and cadence and given the
// environment (terrain and wind)
return fastest;
}
Tuesday, July 31, 12
Using the this keyword
Within an instance method or a constructor, this is a reference to the
current object -- the object whose method or constructor is being called.
Using this with a field:
public class Point { public class Point {
public int x = 0; public int x = 0;
public int y = 0; public int y = 0;
public Point(int a, int b) { public Point(int x, int y) {
x = a; this.x = x;
y = b; this.y = y;
} }
} }
Tuesday, July 31, 12
Using the this keyword
public class Rectangle {
Within a constructor, you can private int x, y;
use the this keyword to call private int width, height;
another constructor in the public Rectangle() {
same class. this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
A different implementation of this(0, 0, width, height);
the Rectangle class. }
public Rectangle(int x, int y, int width,
int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// ...
}
Tuesday, July 31, 12
Controlling access to members of
a class
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method.
There are two levels of access control:
At the top level: public, or package-private (no explicit modifier)
At the member level: public, private, protected, or package-private (no
explicit modifier)
Tuesday, July 31, 12
Controlling access to members of
a class
A class may be declared with the modifier public, that class is visible to
all classes everywhere.
If a class has no modifier (the default, also known as package-private), it
is visible only within its own package.
For members, there are two additional access modifiers: private and
protected.
private: the member can only be accessed in its own class.
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
Tuesday, July 31, 12
Tips on choosing an access level
Use the most restrictive access level that makes sense for a particular
member. Use private unless you have a good reason not to.
Avoid public fields except for constants.
Many examples given in lectures use public fields. This helps to
illustrate some points concisely but is not recommended for
production code.
Public fields limit your flexibility in changing your code.
10
Tuesday, July 31, 12
Instance members, class members
The use of the static keyword to create fields and method that belong to the class rather
than to an instance of a class.
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
Tuesday, July 31, 12
Instance members, class members
Suppose that we want to create a public class Bicycle {
number of Bicycle objects and assign
each a serial number, beginning with private int cadence;
private int gear;
1 for the first object.
private int speed;
This ID number is unique to each // add an instance variable for
object // the object ID
private int id;
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.
}
Such a field is not related to any
Bicycle.numberOfBicycles
objects but to the class as a whole.
12
Tuesday, July 31, 12
Instance members, class members
public class Bicycle {
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
// increment number of Bicycles
// and assign ID number
id = ++numberOfBicycles;
}
// new method to return the ID instance variable
public int getID() {
return id;
}
// ...
}
13
Tuesday, July 31, 12
Instance members, class members
We can also use static method:
public static int getNumberOfBicycles() {
return numberOfBicycles;
}
The static modifier, in combination with the final modifier, is used to
define constants.
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
Tuesday, July 31, 12
Exercises
Exercise 1. Write a class whose instances represent a single playing card
from a deck of card.
Playing cards have two distinguishing properties: rank and suit.
Exercise 2. Write a class whose instances represent a full deck of cards.
Exercise 3. Write a small program to test your deck and card classes.
Create a deck of cards;
Display its cards;
Compare two randomly selected cards from the deck.
15
Tuesday, July 31, 12
Nested classes
We can define a class within another class. Such a class is a nested class:
public class OuterClass { public class OuterClass {
//... //...
static class StaticNestedClass { class InnerClass {
//... //...
} }
} }
A nested class is a member of its enclosing class:
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 nested class can be declared public, protected, private, or package-private.
16
Tuesday, July 31, 12
Nested classes
Why use nested classes?
A way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
17
Tuesday, July 31, 12
Static nested classes
As with class methods and variables, a static nested class is associated
with its outer class.
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.
Access static nested class: OuterClass.StaticNestedClass.
To create an object of the static nested class:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
18
Tuesday, July 31, 12
Inner classes
As with instance methods and variables, an inner class is associated
with its enclosing class and has direct access to that objects methods
and fields.
Because an inner class is associated with an instance, it cannot define
any static members itself.
An instance of InnerClass can exist only within an instance of
OuterClass.
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
19
Tuesday, July 31, 12
Content
Class
Object
More on class
Enum types
Package and the class path
Documentation comments for class
Number and String
20
Tuesday, July 31, 12
Enum types
An enum types is a type whose fields consist of a fixed set of constants.
Compass direction: NORTH, SOUTH, EAST, WEST
Days of the week:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
21
Tuesday, July 31, 12
public class EnumTest {
public static void main(String[] args) {
Day day;
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
public EnumTest(Day day) {
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
this.day = day;
thirdDay.tellItLikeItIs();
}
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
public void tellItLikeItIs() {
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
switch (day) {
sixthDay.tellItLikeItIs();
case MONDAY:
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
System.out.println("Mondays are bad.");
seventhDay.tellItLikeItIs();
break;
}
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
Tuesday, July 31, 12
Enum types
The enum declaration defines a class.
The enum class body can include methods and other fields.
The compiler automatically adds some special methods when it
creates an enum.
Example: Planet is an enum type representing planets in the solar
system.
23
Tuesday, July 31, 12
public enum Planet { public static void main(String[] args) {
MERCURY(3.303e+23, 2.4397e6), if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
VENUS(4.869e+24, 6.0518e6),
System.exit(-1);
EARTH(5.976e+24, 6.37814e6),
}
MARS(6.421e+23, 3.3972e6),
double earthWeight = Double.parseDouble(args[0]);
JUPITER(1.9e+27, 7.1492e7), double mass = earthWeight / EARTH.surfaceGravity();
SATURN(5.688e+26, 6.0268e7), for (Planet p : Planet.values())
URANUS(8.686e+25, 2.5559e7), System.out.printf("Your weight on %s is %f%n", p,
NEPTUNE(1.024e+26, 2.4746e7); p.surfaceWeight(mass));
}
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius; $ java Planet 175
} Your weight on MERCURY is 66.107583
// universal gravitational constant Your weight on VENUS is 158.374842
public static final double G = 6.67300E-11; Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
double surfaceGravity() { Your weight on JUPITER is 442.847567
return G * mass / (radius * radius); Your weight on SATURN is 186.552719
} Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
// ...
}
24
Tuesday, July 31, 12
Exercises
Exercise 4. Rewrite the class Card from Exercise 2 so that it represents
the rank and suit a card with enum types.
Exercise 5. Rewrite the Deck class.
25
Tuesday, July 31, 12