The Java Tutorials (Object-Oriented Programming Concepts)

Start from the beginning
                                        

Bundling code into individual software objects provides a number of benefits, including:

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once

created, an object can be easily passed around inside the system.

Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from

the outside world.

Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program.

This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your

application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world.

If a bolt breaks, you replace it, not the entire machine.

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.

The following Bicycle class is one possible implementation of a bicycle:

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);

}

}

The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion

of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear,

speedUp etc.) define its interaction with the outside world.

You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's

just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects

You've reached the end of published parts.

⏰ Last updated: May 23, 2009 ⏰

Add this story to your Library to get notified about new parts!

The Java Tutorials (Object-Oriented Programming Concepts)Where stories live. Discover now