Object-Oriented Java

¡Supera tus tareas y exámenes ahora con Quizwiz!

Example of an *Interface*

- In its most common form, an *interface* is a group of related *methods* with empty bodies. A bicycle's *behavior*, if specified as an *interface*, might appear as follows: interface Bicycle { // wheel revolutions per minute void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } - Though this code looks very similar to the example *class* named Bicycle, it is important to note that within the interface, the various methods are simply being *invoked*, not *defined*, as they are within the *class* code.

What is an *Instance* of a *Class*?

- In the real world, you'll often find many individual objects all of the same kind. For example, 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. An *instance* of a *class* is known as an *object* in Java.

What is *Inheritance*?

- Object-oriented programming allows *classes* to *inherit* commonly used *state* and *behavior* from other classes. For example, Bicycle could be the *superclass* of more specific *subclasses* such as MountainBike, RoadBike, and TandemBike. - In the Java programming language, each *class* is allowed to have *one* direct *superclass*, and each *superclass* has the potential for an *unlimited* number of *subclasses.*

State & Behavior (Real-world objects)

- Real-world objects share two characteristics: They all have *state* and *behavior*. - For example, 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.

State & Behavior (Software Objects)

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

The *void* Keyword

- The *void* keyword indicates to the *method* that no value is returned after calling that *method*. - Alternatively, we can use *data type keywords* (such as *int*, *char*, etc.) to specify that a *method* should return a value of that type.

Data Encapsulation

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.

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*: 1. At the *top* level—*public*, or *package-private* (no explicit modifier). 2. At the *member* level—*public*, *private*, *protected*, or *package-private* (no explicit modifier). - 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 *(the default, also known as package-private)*, it is visible only within its own *package.* - At the *member* level, you can also use the *public* modifier or no modifier *(package-private)* just as with *top-level* classes, and with the same meaning. 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* (as with package-private) and, in addition, by a *subclass* of its *class* in another *package*.

What is a *Class*?

- A *class* is a blueprint or prototype from which *objects* are created. It can also be described as a set of instructions that describe how a data structure should *behave*. - Java provides us with its own set of pre-defined *classes*, but we are also free to create our own custom *classes*.

Methods

- A *method* is a pre-defined set of instructions. *Methods* are declared within a *class*. Java provides some pre-defined *methods* available to all *classes*, but we can create our own as well. - *Methods* operate on an object's internal *state*, and serve as the primary mechanism for object-to-object communication.

What is a *Package*?

- A *package* is a *namespace* that organizes a set of related *classes* and *interfaces*. Conceptually, you can think of *packages* as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. - Because software written in the Java programming language can be composed of hundreds or thousands of individual *classes*, it makes sense to keep things organized by placing related *classes* and *interfaces* into *packages*.

What is an *Interface*?

- An *interface* is a contract between a *class* and the outside world. When a class implements an interface, it promises to provide the *behavior* published by that interface. - As you've already learned, *objects* define their interaction with the outside world through the *methods* that they expose. *Methods* form the object's *interface* with the outside world. - The buttons on the front of your television set, for example, are the "interface" between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.

What is an *Object*?

- An *object* is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life.

Benefits of Using Objects in Software

- 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.*

Bicycle Example

- Consider a bicycle, modeled as a software object: - 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.

Example of Implementing a *Class*

- Here's a BicycleDemo *class* that creates two separate Bicycle *class objects* and invokes their *methods*: class BicycleDemo { public static void main(String[] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // 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: *bike1* - cadence: 50, speed: 10, gear: 2 *bike2* - cadence: 40, speed: 20, gear: 3

Tips on Choosing an Access Level

- If other programmers use your *class*, you want to ensure that errors from misuse cannot happen. *Access levels* can help you do this. A few tips: - 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 of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.)* - *Public* fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Java API

- The Java platform provides an enormous *class library (a set of packages)* suitable for use in your own applications. This library is known as the *"Application Programming Interface"*, or *"API"* for short. - Its *packages* represent the tasks most commonly associated with general-purpose programming. For example, a String *object* contains *state* and *behavior* for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. - There are literally thousands of *classes* to choose from. This allows you, the programmer, to focus on the *design* of your particular application, rather than the *infrastructure* required to make it work.

Access Levels

- The following link brings you to a table which shows the *access* to *members* permitted by each *modifier*. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html - A *class* always has access to its own *members*. - *Access levels* affect you in two ways. First, when you use *classes* that come from another source, such as the *classes* in the Java platform, *access levels* determine which *members* of those *classes* your own *classes* can use. Second, when you write a *class*, you need to decide what *access level* every *member variable* and every *method* in your *class* should have.

Creating a *Subclass*

- The syntax for creating a *subclass* is simple. At the beginning of your *class declaration*, use the *extends* keyword, followed by the name of the class to *inherit* from: *class* MountainBike *extends* Bicycle { // new fields and methods defining // a mountain bike would go here } - This gives MountainBike all the same *fields* and *methods* as Bicycle, yet allows its code to focus exclusively on the features that make it unique. - This format makes code for your *subclasses* easy to read. However, you must take care to properly document the *state* and *behavior* that each *superclass* defines, since that code will not appear in the source file of each *subclass*.

Class Constructors

- To create the starting state of our *class*, we can add a *class constructor* to it. - A *class constructor* will allow us to create *class instances*. With a *class constructor*, we can instruct the *class* to set up the initial state of an *object*. - If we do not create a *class constructor*, Java provides one by default that does not allow you to set initial information. - The code below demonstrates how a *class constructor* is created: class Car { //The class constructor for the Car class *public Car()* { } }

Implementing an *Interface*

- To implement this *interface*, the name of your *class* would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the *implements* keyword in the *class declaration*: class ACMEBicycle *implements* Bicycle { int cadence = 0; int speed = 0; int gear = 1; // The compiler will now require that *methods* changeCadence, changeGear, speedUp, and applyBrakes all be implemented. Compilation will fail if those *methods* are missing from this *class*. // 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); } } - Implementing an *interface* allows a *class* to become more formal about the *behavior* it promises to provide. - *Interfaces* form a contract between the *class* and the outside world, and this contract is enforced at build time by the compiler. If your *class* claims to implement an *interface*, all *methods* defined by that *interface* must appear in its source code before the *class* will successfully compile.

Instance Variables

- When we create a new *class*, we probably have specific details that we want the *class* to include. We save those specific details into *instance variables*. - Here is an *instance variable* in the Car *class* that describes a detail that we might want to associate with a car: class Car { //Using instance variables to model our Car class after a real-life car int modelYear; public Car() { } } - In the example above, we created the *instance variable* named *modelYear*. *Instance variables* model real-world car attributes, such as the model year of a car.

Example of a *Class*

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 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 belongs to some other *class* in your application.


Conjuntos de estudio relacionados

PUBH 358: 3.2 Nutrition and Eating Disorders

View Set

Health Care Delivery and Diversity/LGBTQ/Communication

View Set

Article 20 - What is Beautiful is good

View Set

History; Challenges Today: Technology

View Set