Академический Документы
Профессиональный Документы
Культура Документы
11
What Is a Class?
In the real world, many individual objects all
of the same kind.
There may be thousands of bicycles in
existence. Each bicycle was built from the
same set of blueprints and therefore contains
the same components.
In object-oriented terms, bicycle is an
instance of the class of objects known as
bicycles. A class is the blueprint from which
individual objects are created.
2
Point Class
public class Point {
public int x = 0;
public int y = 0;
// a constructor!
public Point(int a, int b) {
x = a; y = b; }
}
3
Rectangle class
4
Rectangle class …
5
Creating Object
• As you know, a class provides the blueprint
for objects; you create an object from a
class.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
8
Information Hiding
public class Point {
private int x = 0;
private int y = 0;
// a constructor!
public Point(int a, int b) {
x = a; y = b; }
public int getX() {
return x; }
public int getY() {
return y; }
public void setX(int ax) {
x = ax; }
public void setY(int ay) {
y = ay; }
}
9
Bicycle class
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
12
Class and Object Benefits
13
Static Attribute (class var)
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
Bicycle.numberOfBicycles
14
Static Method
class Bicycle {
...
static int numberOfBicycles = 0;
static int getNumberOfBicycles() {
return numberOfBicycles; }
...
}
Bicycle.getNumberOfBicycles()
15
Reference ‘this’
• Reference ke current object: this
class Point {
private int x = 0;
private int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
...
}
16
Reference ‘this’
class Rectangle {
...
public Rectangle() {
this(0,0,0,0);
}
public Rectangle(int x, int y, int width,
int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
17