What Is an Object?
Objects are key to understanding object-oriented technology. Real-world objects share two characteristics: They all have state and behavior.
Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
Java Classes
Below is an example of class Bicycle as implemented in Java.
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
Below is an example showing you how to create a Bicycle object and use it.
public class BicycleObjectDemo {
public static void main(String[] args) {
// Declare and create a bicycle object
Bicycle bicyce1 = new Bicycle();
//display the bicycle's current state
bicycle1.printStates();
//change the bicycle's speed
bicycle1.speedUp(10);
//display the bicycle's current state again
bicycle1.printStates(); System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}
Constructors
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, the above Bicycle class can have one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
To create a new Bicycle object called myBike, a constructor is called by the new operator:
Bicycle myBike = new Bicycle(30, 0, 8);
new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.
Controlling Access to Members of a Class
Access level modifiers determine whether other classes can use a particular field or invoke a particular method.
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier, it is visible only within its own package.
At the member level, you can also use the public modifier, to mean that the class member is visible to all classes everywhere. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package and, in addition, by a subclass of its class in another package.
he following table shows the access to members permitted by each modifier.
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public |
Y | Y | Y | Y |
protected |
Y | Y | Y | N |
no modifier | Y | Y | N | N |
private |
Y | N | N |
N |
Creating Objects
As you know, a class provides the blueprint for objects; you can 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);
The first line creates an object of the Point
class, and the second and third lines each create an object of the Rectangle
class.
Each of these statements has three parts:
- Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
- Instantiation: The new keyword is a Java operator that creates the object.
- Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Referenceing an Object's Fields
Object fields are accessed by their name. You must use a name that is unambiguous.
You may use a simple name for a field within its own class. For example, we can add a statement within the Rectangle
class that prints the width
and height
:
System.out.println("Width and height are: " + width + ", " + height);
In this case, width
and height
are simple names.
Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
For example, the code below is outside the code for the Rectangle class. So to refer to the origin, width, and height fields within the Rectangle object named rectOne, we must use the names rectOne.origin, rectOne.width, and rectOne.height, respectively:
System.out.println("Width of rectOne: " + rectOne.width); System.out.println("Height of rectOne: " + rectOne.height);
Calling an Object's Methods
You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList);
or:
objectReference.methodName();
The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the the cosw ro invoke these two methods:
System.out.println("Area of rectOne: " + rectOne.getArea()); ... rectTwo.move(40, 72);
Passing Reference Data Type Arguments
When parameters of primitive data types such as int, boolean, double (but not String because String is an object class) are passed into methods, they are passed into the method by "value". What this means is that when the methods make some changes to these values, and when the method returns, the changes made within the method will not persist.
For example:
public int addition(int x, int y) {
x = 4;
y = 5;
return x+y;
}
If you invoke the above method:
int x = 2;
int y = 2;
int z = addition(x, y);
System.out.println("x="+x+" y="+y);
You will see x and y will print as 2 and 2.
When object parameters (including array parameters because array are just special types of objects) are passed into methods, they are passed into the method by "reference". When the methods make some changes to their internal data and when the method returns, the passed-in reference still references the same object as before. Therefore, the changes made within the method will persist.
For example, consider a method in a class that moves Circle
objects:
public void moveCircle(Circle circle, int deltaX, int deltaY) { // code to move origin of circle to x+deltaX, y+deltaY circle.setX(circle.getX() + deltaX); circle.setY(circle.getY() + deltaY); }
Let the method be invoked with these arguments:
moveCircle(myCircle, 23, 56)
Inside the method, circle
refers to myCircle
. The method changes the x and y coordinates of the object that circle
references (i.e., myCircle
) by 23 and 56, respectively. These changes will persist when the method returns. So after you have called the method, if you print out the values of the x and y of the object myCircle, it will be the changed value.
However, if within the method, you assign a new object to the reference, that new object, and any changes you make to that new object, will not persist after the method returns.
For example, if the moveCircle is implemented as below:
public void moveCircle(Circle circle, int deltaX, int deltaY) { // code to assign a new object to circle circle = new Circle(circle.getX()+deltaX, circle.getY()+deltaY); }
Then when the method returns, and you print out the values of the x and y of the object myCircle, it will NOT be the changed value in the method.
Once you've created an object, you probably want to use it for something. You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action.
Lab: Do the 2 geometric objects overlap?
Design a Java program with a class for a rectangle. Then your program will prompt the user to enter basic attributes about 2 rectangles and create an object of each rectangle. Then your program will do some calculation and tell the user whether the 2 geometric objects overlap. To make this program more interesting, if the 2 objects overlap, calculate a value to move the 2 objects apart and display to the user what are the new values.