Java OOP Concepts: Classes and Objects PDF
Document Details
Uploaded by CharitableWormhole2937
City, University of London
Tags
Summary
This document introduces the concept of classes and objects in object-oriented programming (OOP) using the Java language. It explains how software objects model real-world entities, the relationship between classes and objects, and the importance of data encapsulation in OOP. The document also details how to declare classes, implement object methods, and use objects within a program.
Full Transcript
**1. Classes and Objects** **What is an object?** An object is a software bundle of variables and related methods that represent states and behaviors. Software objects are often used to model the real-world objects that you find in everyday life. Objects are key to understanding *object-oriented...
**1. Classes and Objects** **What is an object?** An object is a software bundle of variables and related methods that represent states and behaviors. Software objects are often used to model the real-world objects that you find in everyday life. Objects are key to understanding *object-oriented* technology. Look around right now and you\'ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. 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. Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: \"What possible states can this object be in?\" and \"What possible behavior can this object perform?\". Make sure to write down your observations. As you do, you\'ll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming. A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle. A software object. Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in *fields* (variables in some programming languages) and exposes its behavior through *methods* (functions in some programming languages). Methods operate on an object\'s internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object\'s methods is known as *data encapsulation* --- a fundamental principle of object-oriented programming. Consider a bicycle. By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. ![A picture of an object, with bibycle methods and instance variables.](media/image2.gif) A bicycle modeled as a software object. Bundling code into individual software objects provides a number of benefits, including: 1. 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. 2. Information-hiding: By interacting only with an object\'s methods, the details of its internal implementation remain hidden from the outside world. 3. 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. 4. 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?** A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior. In the real world, you\'ll often find many individual objects all of the same kind. For example, there may be thousands of 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. **Declaring a class** Implementing a class is done in the following way: class *MyClass* { // field, constructor, and // method declarations } This is a *class declaration*. The *class body* (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects. The following Bicycle class is one possible implementation of a bicycle: class Bicycle { int cadence; int speed; int gear; 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 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 belongs to some other class in your application. The Bicycle class uses the following lines of code to define its fields: int cadence; int gear; int speed; Field declarations are composed of three components, in order: 1. Zero or more modifiers, that we will discuss in the next session. 2. The field\'s type. 3. The field\'s name. The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). **2. Basics to use an object** Now that we have seen how to declare a class, we will see how to instantiate it by creating an abject. **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 class Bicycle can be provided with one constructor: Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } **Creating a new object** 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. A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects. **Using an object: accessing members** There are a lot of subtilties about accessing members of classes and objects, that we will discuss over the next few sessions. For now, you only need to remember the following: 1. To use a member of a class within the class itself: use directly its name. 2. To access a field or method of an object that has been created: use the name of the object followed by a dot followed by the member\'s name. Consider again the following class Bicycle: class Bicycle { int cadence; int speed; int gear; Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } 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); } } Here\'s a BicycleDemo class that creates two separate Bicycle objects and invokes their methods: class BicycleDemo { public static void main(String\[\] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(0,0,1); Bicycle bike2 = new Bicycle(0,0,1); // Invoke methods on // those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } } The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: