Classes and Objects in Java. What Is an Object?. An object is a software bundle of related state and...

Post on 19-Dec-2015

219 views 2 download

Tags:

Transcript of Classes and Objects in Java. What Is an Object?. An object is a software bundle of related state and...

Classes and Objects in Java

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. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

Objects• Objects are key to understanding object-oriented technology. • In the world around you, you'll find many examples of real-world objects:

your dog, your desk, your television set, your Square.

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

• Squares 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.

Exercise

• Consider the elements of a Dog object in terms of static attributes and methods

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

• 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

Advantages of Software Objects• 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?

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

Instantiation

• In the real world, you'll often find many individual objects all of the same kind.

• There may be thousands of other Squares in existence, all of the same make and model. Each Square was built from the same set of blueprints and therefore contains the same components.

• In object-oriented terms, we say that your Square is an instance of the class of objects known as Squares.

• A class is the blueprint from which individual objects are created.

classes are defined in the following way:

class MyClass {

//field, constructor, and method declarations

}

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.

Example of a class declarationpublic class Square { // the Square class has two fields public int side; public String colour; // the Square class has one constructor public Square(int startside, String startcolour) { side = startside; colour = startcolour; }

// the Square class has three methods public void changecolour(String newcolour) { colour = newcolour; }

public void decreasesize(int decrement) { side -= decrement; }

public void increasesize(int increment) { side += increment; } }

Exercise

• Create a circle class which has 1 constructor and 1 method to output circle area.

Components of Class Declarations

• . • In general, class declarations can include these components, in

order: • Modifiers such as public, private, and a number of others that you

will encounter later. • The class name, with the initial letter capitalized by convention. • The name of the class's parent (superclass), if any, preceded by the

keyword extends. A class can only extend (subclass) one parent. • A comma-separated list of interfaces implemented by the class, if

any, preceded by the keyword implements. A class can implement more than one interface.

• The class body, surrounded by braces, {}.

Note Interfaces

• 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. This section defines a simple interface and explains the necessary changes for any class that implements it

What Is an Interface?

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

• In its most common form, an interface is a group of related methods with empty bodies.

Declaring Member Variables

• There are several kinds of variables:

• Member variables in a class—these are called fields.

• Variables in a method or block of code—these are called local variables.

• Variables in method declarations—these are called parameters.

Example Field

public int side;

public String colour;

Example Local Variable

public void decreasesizebyfive() {

int decrementa = 5;

side -= decrementa; }

int decrementa = 5; is the local Variable

Declaration within the body of a method

Variables in method declarations—these are called parameters.

public void changecolour(String newcolour) {

colour = newcolour; }

String newcolour is a parameter declaration

Field declarations

• Example• public int gear; • public int speed; • Field declarations are composed of three

components, in order: • Zero or more modifiers, such as public or

private. • The field's type e.g. int float etc• The field's name. e.g. gear

Types

• All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you can use reference types, such as strings, arrays, or objects.

Variable Naming Conventions• Variable names are case-sensitive. A variable's name can be any

legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".

• The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all.

• You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it.

• A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

Subsequent Characters

• Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well.

• When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g.

• Also keep in mind that the name you choose must not be a keyword or reserved word.

The Name

• The name you choose consists of only one word, spell that word in all lowercase letters.

• If it consists of more than one word, capitalize the first letter of each subsequent word.

• The names gearRatio and currentGear are prime examples of this convention.

• If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character.

• By convention, the underscore character is never used elsewhere.

Public and PrivateAccess Modifiers

• Access Modifiers• The first (left-most) modifier used lets you control what other classes

have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later.

• public modifier—the field is accessible from all classes. • private modifier—the field is accessible only within its own class. • In the spirit of encapsulation, it is common to make fields private.

This means that they can only be directly accessed from within the class.

• If we still need access to these values, however, then this can be done indirectly by adding public methods that obtain the field values for us:

Public

• Public Components for example Steering Wheel , Door Handles etc

• Not worried about Sparkplugs Electrics Etc

• Private Components

Consider the following Class(from Java Documentation)

• public class Bicycle { • private int cadence; • private int gear; • private int speed; • public Bicycle(int startCadence, int startSpeed, int startGear) { • gear = startGear; • cadence = startCadence; • speed = startSpeed; • } • public int getCadence() {• return cadence; } • public void setCadence(int newValue) { • cadence = newValue; } • public int getGear() {• return gear; } • public void setGear(int newValue) { • gear = newValue; } • public int getSpeed() { • return speed; } • public void applyBrake(int decrement) { • speed -= decrement; } • public void speedUp(int increment) {• speed += increment; } }

In this example

• We see Private Variables

• Typically they are only accessed from within class

• However they are retrieved by public methods

Method Declarations• method declarations have six components, in order: • Modifiers—such as public, private, and others you will learn about

later. • The return type—the data type of the value returned by the method,

or void if the method does not return a value. • The method name—the rules for field names apply to method

names as well, but the convention is a little different. • The parameter list in parenthesis—a comma-delimited list of input

parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.

• An exception list—to be discussed later. • The method body, enclosed between braces—the method's code,

including the declaration of local variables, goes here.

Example

• public int getCadence() {• return cadence; } • Modifier Public• Return type is int• Method name is getCadence• no parameters, you must use empty

parentheses ().• Method body enclosed in {} is• return cadence;

Another Example

• public void setCadence(int newValue) {

• cadence = newValue; }

• Modifier public

• Return type void

• Name setCadence

• Parameter int newValue

• Body cadence = newValue;

When Designing a Class

• The following steps should be followed• Identify field attributes and their associated

types• Write the constructor method• Identify operations necessary to change the data

in the class. Implement each operation by adding a public method to make the change

• Identify observer methods that can be used to return information about the attributes in the class.

• Write a display method that writes data to the screen, if required.

Exercise

• Write and implement a class called date which represents a calendar date.

Further exercises

• Add methods to your class which

• 1) print out a given date in the form e.g.

• “Today is the 5th day of January, 2008”

for the data d = 5, m=1,y=2008

2) A method which prints out the successor date for a given date