c0 review core java1

101
Java 1 fundamental Java 1 fundamental reviews reviews

Upload: tam53pm1

Post on 19-Jan-2015

430 views

Category:

Technology


3 download

DESCRIPTION

 

TRANSCRIPT

Page 1: C0 review core java1

Java 1 fundamental reviewsJava 1 fundamental reviews

Page 2: C0 review core java1

Primitive DataPrimitive Data

There are exactly eight primitive data types in JavaThere are exactly eight primitive data types in Java

Four of them represent integers:Four of them represent integers: bytebyte, , shortshort, , intint, , longlong

Two of them represent floating point numbers:Two of them represent floating point numbers: floatfloat, , doubledouble

One of them represents characters:One of them represents characters: charchar

And one of them represents boolean values:And one of them represents boolean values: booleanboolean

Page 3: C0 review core java1

3

Introduction to ObjectsIntroduction to Objects

Initially, we can think of an Initially, we can think of an objectobject as a collection of services that as a collection of services that we can tell it to perform for uswe can tell it to perform for us

The services are defined by methods in a class that defines the The services are defined by methods in a class that defines the objectobject

Example, we invoked the Example, we invoked the printlnprintln method of the method of the System.outSystem.out object: object:

System.out.println ("Whatever you are, be a good one.");

objectobject methodmethodInformation provided to the methodInformation provided to the method

(parameters)(parameters)

Page 4: C0 review core java1

4

AbstractionAbstraction

An An abstractionabstraction hides (or ignores) the right details at the right hides (or ignores) the right details at the right timetime

An object is abstract in that we don't really have to think about An object is abstract in that we don't really have to think about its internal details in order to use itits internal details in order to use it

We don't have to know how the We don't have to know how the printlnprintln method works in method works in order to invoke itorder to invoke it

Therefore, we can write complex software by organizing it Therefore, we can write complex software by organizing it carefully into classes and objectscarefully into classes and objects

Page 5: C0 review core java1

Creating ObjectsCreating Objects

A variable either holds a primitive type, or it holds a A variable either holds a primitive type, or it holds a referencereference to to an objectan object

A class name can be used as a type to declare an A class name can be used as a type to declare an object object reference variablereference variable

String title;

No object has been created with this declarationNo object has been created with this declaration An object reference variable holds the address of an objectAn object reference variable holds the address of an object The object itself must be created separatelyThe object itself must be created separately

Page 6: C0 review core java1

Creating ObjectsCreating Objects

We use the We use the newnew operator to create an object operator to create an object

title = new String ("Java Software Solutions");

This calls the This calls the StringString constructorconstructor, which is, which isa special method that sets up the objecta special method that sets up the object

Creating an object is called Creating an object is called instantiationinstantiation

An object is an An object is an instanceinstance of a particular class of a particular class

Page 7: C0 review core java1
Page 8: C0 review core java1

Flow of ControlFlow of Control

Unless indicated otherwise, the order of statement execution Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they through a method is linear: one after the other in the order they are writtenare written

Some programming statements modify that order, allowing us Some programming statements modify that order, allowing us to:to: decide whether or not to execute a particular statement, ordecide whether or not to execute a particular statement, or perform a statement over and over repetitivelyperform a statement over and over repetitively

The order of statement execution is called the The order of statement execution is called the flow of controlflow of control

Page 9: C0 review core java1

Conditional StatementsConditional Statements

A A conditional statementconditional statement lets us choose which statement will be lets us choose which statement will be executed nextexecuted next

Therefore they are sometimes called Therefore they are sometimes called selection statementsselection statements

Conditional statements give us the power to make basic Conditional statements give us the power to make basic decisionsdecisions

Java's conditional statements are the Java's conditional statements are the if statementif statement, the , the if-else if-else statementstatement, and the , and the switch statementswitch statement

Page 10: C0 review core java1

Repetition StatementsRepetition Statements

Repetition statementsRepetition statements allow us to execute a statement multiple allow us to execute a statement multiple times repetitivelytimes repetitively

They are often simply referred to as They are often simply referred to as loopsloops

Like conditional statements, they are controlled by boolean Like conditional statements, they are controlled by boolean expressionsexpressions

Java has three kinds of repetition statements: the Java has three kinds of repetition statements: the while loopwhile loop, the , the do loopdo loop, and the , and the for loopfor loop

The programmer must choose the right kind of loop for the The programmer must choose the right kind of loop for the situationsituation

Page 11: C0 review core java1
Page 12: C0 review core java1

12

Writing ClassesWriting Classes

Focuses :Focuses : class declarationsclass declarations method declarationsmethod declarations instance variablesinstance variables encapsulationencapsulation method overloadingmethod overloading

Page 13: C0 review core java1

13

ObjectsObjects

An object has:An object has: statestate - descriptive characteristics - descriptive characteristics behaviorsbehaviors - what it can do (or be done to it) - what it can do (or be done to it)

For example, consider a coin that can be flipped so that it's face For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails"shows either "heads" or "tails"

The state of the coin is its current face (heads or tails)The state of the coin is its current face (heads or tails) The behavior of the coin is that it can be flippedThe behavior of the coin is that it can be flipped Note that the behavior of the coin might change its stateNote that the behavior of the coin might change its state

Page 14: C0 review core java1

14

ClassesClasses

A A classclass is a blueprint of an object is a blueprint of an object

It is the model or pattern from which objects are createdIt is the model or pattern from which objects are created

For example, the For example, the StringString class is used to define class is used to define StringString objectsobjects

Each Each StringString object contains specific characters (its state) object contains specific characters (its state)

Each Each StringString object can perform services (behaviors) such as object can perform services (behaviors) such as toUpperCasetoUpperCase

Page 15: C0 review core java1

ClassesClasses

The The StringString class was provided for us by the Java standard class was provided for us by the Java standard class libraryclass library

But we can also write our own classes that define specific But we can also write our own classes that define specific objects that we needobjects that we need

For example, suppose we wanted to write a program that For example, suppose we wanted to write a program that simulates the flipping of a coinsimulates the flipping of a coin

We could write a We could write a CoinCoin class to represent a coin object class to represent a coin object

Page 16: C0 review core java1

ClassesClasses

A class contains data declarations and method declarationsA class contains data declarations and method declarations

int x, y;char ch;

Data declarationsData declarations

Method declarationsMethod declarations

Page 17: C0 review core java1

Data ScopeData Scope

The The scopescope of data is the area in a program in which that data of data is the area in a program in which that data can be used (referenced)can be used (referenced)

Data declared at the class level can be used by all methods in Data declared at the class level can be used by all methods in that classthat class

Data declared within a method can only be used in that methodData declared within a method can only be used in that method

Data declared within a method is called Data declared within a method is called local datalocal data

Page 18: C0 review core java1

Writing MethodsWriting Methods

A A method declarationmethod declaration specifies the code that will be executed specifies the code that will be executed when the method is invoked (or called)when the method is invoked (or called)

When a method is invoked, the flow of control jumps to the When a method is invoked, the flow of control jumps to the method and executes its codemethod and executes its code

When complete, the flow returns to the place where the method When complete, the flow returns to the place where the method was called and continueswas called and continues

The invocation may or may not return a value, depending on The invocation may or may not return a value, depending on how the method was definedhow the method was defined

Page 19: C0 review core java1

Method Control FlowMethod Control Flow

The called method could be within the same class, in which The called method could be within the same class, in which case only the method name is neededcase only the method name is needed

myMethod();

myMethodcompute

Page 20: C0 review core java1

doIt

helpMe

helpMe();

obj.doIt();

main

Method Control FlowMethod Control Flow

The called method could be part of another class or objectThe called method could be part of another class or object

Page 21: C0 review core java1

21

EncapsulationEncapsulation You can take one of two views of an object:You can take one of two views of an object:

internal - the structure of its data, the algorithms used by its internal - the structure of its data, the algorithms used by its methodsmethods

external - the interaction of the object with other objects in the external - the interaction of the object with other objects in the programprogram

From the external view, an object is an From the external view, an object is an encapsulatedencapsulated entity, providing entity, providing a set of specific servicesa set of specific services

These services define the These services define the interfaceinterface to the object to the object

Recall from Chapter 2 that an object is an Recall from Chapter 2 that an object is an abstractionabstraction, hiding details , hiding details from the rest of the systemfrom the rest of the system

Page 22: C0 review core java1

22

EncapsulationEncapsulation

An object should be An object should be self-governingself-governing

Any changes to the object's state (its variables) should be Any changes to the object's state (its variables) should be accomplished by that object's methodsaccomplished by that object's methods

We should make it difficult, if not impossible, for one object to We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state"reach in" and alter another object's state

The user, or The user, or clientclient, of an object can request its services, but it , of an object can request its services, but it should not have to be aware of how those services are should not have to be aware of how those services are accomplishedaccomplished

Page 23: C0 review core java1

23

EncapsulationEncapsulation

An encapsulated object can be thought of as a An encapsulated object can be thought of as a black boxblack box Its inner workings are hidden to the client, which only invokes Its inner workings are hidden to the client, which only invokes

the interface methodsthe interface methods

ClientClient Methods

Data

Page 24: C0 review core java1

24

Visibility ModifiersVisibility Modifiers

In Java, we accomplish encapsulation through the appropriate In Java, we accomplish encapsulation through the appropriate use of use of visibility modifiersvisibility modifiers

A A modifiermodifier is a Java reserved word that specifies particular is a Java reserved word that specifies particular characteristics of a method or data valuecharacteristics of a method or data value

We've used the modifier We've used the modifier finalfinal to define a constant to define a constant

Java has three visibility modifiers: Java has three visibility modifiers: publicpublic, , privateprivate, and , and protectedprotected

We will discuss the We will discuss the protectedprotected modifier later modifier later

Page 25: C0 review core java1

25

Visibility ModifiersVisibility Modifiers

Members of a class that are declared with Members of a class that are declared with public visibilitypublic visibility can can be accessed from anywherebe accessed from anywhere

Members of a class that are declared with Members of a class that are declared with private visibilityprivate visibility can can only be accessed from inside the classonly be accessed from inside the class

Members declared without a visibility modifier have Members declared without a visibility modifier have default default visibilityvisibility and can be accessed by any class in the same and can be accessed by any class in the same packagepackage

Java modifiers are discussed in detail in Appendix FJava modifiers are discussed in detail in Appendix F

Page 26: C0 review core java1

26

Visibility ModifiersVisibility Modifiers

As a general rule, no object's data should be declared with As a general rule, no object's data should be declared with public visibilitypublic visibility

Methods that provide the object's services are usually declared Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clientswith public visibility so that they can be invoked by clients

Public methods are also called Public methods are also called service methodsservice methods

A method created simply to assist a service method is called a A method created simply to assist a service method is called a support methodsupport method

Since a support method is not intended to be called by a client, Since a support method is not intended to be called by a client, it should not be declared with public visibilityit should not be declared with public visibility

Page 27: C0 review core java1

Method Declarations RevisitedMethod Declarations Revisited

A method declaration begins with a A method declaration begins with a method headermethod header

char calc (int num1, int num2, String message)

methodmethodnamename

returnreturntypetype

parameter listparameter list

The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter

The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument

Page 28: C0 review core java1

Method DeclarationsMethod Declarations

The method header is followed by the The method header is followed by the method bodymethod body

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

The return expression must beThe return expression must beconsistent with the return typeconsistent with the return type

sumsum and and resultresultare are local datalocal data

They are created each They are created each time the method is called, time the method is called, and are destroyed when and are destroyed when it finishes executingit finishes executing

Page 29: C0 review core java1

29

The return StatementThe return Statement

The The return typereturn type of a method indicates the type of value that the of a method indicates the type of value that the method sends back to the calling locationmethod sends back to the calling location

A method that does not return a value has aA method that does not return a value has a void void return typereturn type

The The return statementreturn statement specifies the value that will be returned specifies the value that will be returned

Its expression must conform to the return typeIts expression must conform to the return type

Page 30: C0 review core java1

ParametersParameters Each time a method is called, the Each time a method is called, the actual argumentsactual arguments in the invocation are copied in the invocation are copied

into the formal argumentsinto the formal arguments

char calc (int num1, int num2, String message)

{ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

ch = obj.calc (25, count, "Hello");

Page 31: C0 review core java1

31

Constructors RevisitedConstructors Revisited

Recall that a constructor is a special method that is used to set Recall that a constructor is a special method that is used to set up a newly created objectup a newly created object

When writing a constructor, remember that:When writing a constructor, remember that: it has the same name as the classit has the same name as the class it does not return a valueit does not return a value it has no return type, not evenit has no return type, not even void void it often sets the initial values of instance variables it often sets the initial values of instance variables

The programmer does not have to define a constructor for a The programmer does not have to define a constructor for a classclass

Page 32: C0 review core java1

Writing ClassesWriting Classes

See See BankAccounts.javaBankAccounts.java (page 188)(page 188) See See Account.java Account.java (page 189)(page 189)

An An aggregate objectaggregate object is an object that contains references to is an object that contains references to other objectsother objects

An An AccountAccount object is an aggregate object because it contains object is an aggregate object because it contains a reference to a a reference to a StringString object (that holds the owner's name) object (that holds the owner's name)

An aggregate object represents a An aggregate object represents a has-a relationshiphas-a relationship A bank account A bank account has ahas a name name

Page 33: C0 review core java1

Writing ClassesWriting Classes

Sometimes an object has to interact with other objects of the Sometimes an object has to interact with other objects of the same typesame type

For example, we might add two For example, we might add two RationalRational number objects number objects together as follows:together as follows:

r3 = r1.add(r2);

One object (One object (r1r1) is executing the method and another () is executing the method and another (r2r2) is ) is passed as a parameterpassed as a parameter

See See RationalNumbers.javaRationalNumbers.java (page 196)(page 196) See See Rational.java Rational.java (page 197)(page 197)

Page 34: C0 review core java1

34

Overloading MethodsOverloading Methods

Method overloadingMethod overloading is the process of using the same method is the process of using the same method name for multiple methodsname for multiple methods

The The signaturesignature of each overloaded method must be unique of each overloaded method must be unique

The signature includes the number, type, and order of the The signature includes the number, type, and order of the parametersparameters

The compiler must be able to determine which version of the The compiler must be able to determine which version of the method is being invoked by analyzing the parametersmethod is being invoked by analyzing the parameters

The return type of the method is The return type of the method is notnot part of the signature part of the signature

Page 35: C0 review core java1

Overloading MethodsOverloading Methods

float tryMe (int x){ return x + .375;}

Version 1Version 1

float tryMe (int x, float y){ return x*y;}

Version 2Version 2

result = tryMe (25, 4.32)

InvocationInvocation

Page 36: C0 review core java1

36

Overloaded MethodsOverloaded Methods

TheThe println println method is overloaded:method is overloaded:

println (String s)println (String s)

println (int i)println (int i)

println (double d)println (double d)

etc.etc.

The following lines invoke different versions of theThe following lines invoke different versions of the println println method:method:

System.out.println ("The total is:");System.out.println ("The total is:");

System.out.println (total);System.out.println (total);

Page 37: C0 review core java1

37

Overloading MethodsOverloading Methods

Constructors can be overloadedConstructors can be overloaded An overloaded constructor provides multiple ways to set up a An overloaded constructor provides multiple ways to set up a

new objectnew object

Page 38: C0 review core java1

Method DecompositionMethod Decomposition

A method should be relatively small, so that it can be readily A method should be relatively small, so that it can be readily understood as a single entityunderstood as a single entity

A potentially large method should be decomposed into several A potentially large method should be decomposed into several smaller methods as needed for claritysmaller methods as needed for clarity

Therefore, a service method of an object may call one or more Therefore, a service method of an object may call one or more support methods to accomplish its goalsupport methods to accomplish its goal

Page 39: C0 review core java1
Page 40: C0 review core java1

40

Enhancing ClassesEnhancing Classes

We can now explore various aspects of classes and objects in We can now explore various aspects of classes and objects in more detailmore detail

Focuses :Focuses : object references and aliasesobject references and aliases passing objects as parameterspassing objects as parameters the static modifierthe static modifier nested classesnested classes interfaces and polymorphisminterfaces and polymorphism events and listenersevents and listeners animationanimation

Page 41: C0 review core java1

41

ReferencesReferences

Recall from Chapter 2 that an object reference holds the Recall from Chapter 2 that an object reference holds the memory address of an objectmemory address of an object

Rather than dealing with arbitrary addresses, we often depict a Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an objectreference graphically as a “pointer” to an object

ChessPiece bishop1 = new ChessPiece();

bishop1

Page 42: C0 review core java1

42

Assignment RevisitedAssignment Revisited

The act of assignment takes a copy of a value and stores it in a The act of assignment takes a copy of a value and stores it in a variablevariable

For primitive types:For primitive types:

num2 = num1;

Before

num1

5

num2

12

After

num1

5

num2

5

Page 43: C0 review core java1

43

Reference AssignmentReference Assignment

For object references, assignment copies the memory location:For object references, assignment copies the memory location:

bishop2 = bishop1;

Before

bishop1 bishop2

After

bishop1 bishop2

Page 44: C0 review core java1

44

AliasesAliases

Two or more references that refer to the same object are called Two or more references that refer to the same object are called aliasesaliases of each other of each other

One object (and its data) can be accessed using different One object (and its data) can be accessed using different variablesvariables

Aliases can be useful, but should be managed carefullyAliases can be useful, but should be managed carefully

Changing the object’s state (its variables) through one Changing the object’s state (its variables) through one reference changes it for all of its aliasesreference changes it for all of its aliases

Page 45: C0 review core java1

45

Garbage CollectionGarbage Collection

When an object no longer has any valid references to it, it can When an object no longer has any valid references to it, it can no longer be accessed by the programno longer be accessed by the program

It is useless, and therefore called It is useless, and therefore called garbagegarbage

Java performs Java performs automatic garbage collectionautomatic garbage collection periodically, periodically, returning an object's memory to the system for future usereturning an object's memory to the system for future use

In other languages, the programmer has the responsibility for In other languages, the programmer has the responsibility for performing garbage collectionperforming garbage collection

Page 46: C0 review core java1

Passing Objects to MethodsPassing Objects to Methods

Parameters in a Java method are Parameters in a Java method are passed by valuepassed by value

This means that a copy of the actual parameter (the value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method passed in) is stored into the formal parameter (in the method header)header)

Passing parameters is essentially an assignmentPassing parameters is essentially an assignment

When an object is passed to a method, the actual parameter When an object is passed to a method, the actual parameter and the formal parameter become aliases of each otherand the formal parameter become aliases of each other

Page 47: C0 review core java1

Passing Objects to MethodsPassing Objects to Methods

What you do to a parameter inside a method may or may not What you do to a parameter inside a method may or may not have a permanent effect (outside the method)have a permanent effect (outside the method)

See See ParameterPassing.javaParameterPassing.java (page 226)(page 226) See See ParameterTester.javaParameterTester.java (page 228)(page 228) See See Num.java Num.java (page 230)(page 230)

Note the difference between changing the reference and Note the difference between changing the reference and changing the object that the reference points tochanging the object that the reference points to

Page 48: C0 review core java1

48

The static ModifierThe static Modifier

In Chapter 2 we discussed static methods (also called class In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather than methods) that can be invoked through the class name rather than through a particular objectthrough a particular object

For example, the methods of the For example, the methods of the MathMath class are static class are static

To make a method static, we apply the To make a method static, we apply the staticstatic modifier to the modifier to the method definitionmethod definition

The The staticstatic modifier can be applied to variables as well modifier can be applied to variables as well

It associates a variable or method with the class rather than an It associates a variable or method with the class rather than an objectobject

Page 49: C0 review core java1

49

Static MethodsStatic Methods

public static int triple (int num){ int result; result = num * 3; return result;}

class Helperclass Helper

Because it is static, the method could be invoked as:Because it is static, the method could be invoked as:

value = Helper.triple (5);

Page 50: C0 review core java1

50

Static MethodsStatic Methods

The order of the modifiers can be interchanged, but by The order of the modifiers can be interchanged, but by convention visibility modifiers come first convention visibility modifiers come first

Recall that the Recall that the mainmain method is static; it is invoked by the method is static; it is invoked by the system without creating an objectsystem without creating an object

Static methods cannot reference instance variables, because Static methods cannot reference instance variables, because instance variables don't exist until an object existsinstance variables don't exist until an object exists

However, they can reference static variables or local variablesHowever, they can reference static variables or local variables

Page 51: C0 review core java1

51

Static VariablesStatic Variables

Static variables are sometimes called Static variables are sometimes called class variablesclass variables

Normally, each object has its own data spaceNormally, each object has its own data space

If a variable is declared as static, only one copy of the variable If a variable is declared as static, only one copy of the variable existsexists

private static float price;

Memory space for a static variable is created as soon as the Memory space for a static variable is created as soon as the class in which it is declared is loadedclass in which it is declared is loaded

Page 52: C0 review core java1

Static VariablesStatic Variables

All objects created from the class share access to the static All objects created from the class share access to the static variablevariable

Changing the value of a static variable in one object changes it Changing the value of a static variable in one object changes it for all others for all others

Static methods and variables often work togetherStatic methods and variables often work together

See See CountInstances.javaCountInstances.java (page 233)(page 233) See See MyClass.javaMyClass.java (page 234)(page 234)

Page 53: C0 review core java1

Nested ClassesNested Classes

In addition to a class containing data and methods, it can also In addition to a class containing data and methods, it can also contain other classescontain other classes

A class declared within another class is called a A class declared within another class is called a nested classnested class

Outer Class

NestedClass

Page 54: C0 review core java1

Nested ClassesNested Classes

A nested class has access to the variables and methods of the A nested class has access to the variables and methods of the outer class, even if they are declared privateouter class, even if they are declared private

In certain situations this makes the implementation of the In certain situations this makes the implementation of the classes easier because they can easily share informationclasses easier because they can easily share information

Furthermore, the nested class can be protected by the outer Furthermore, the nested class can be protected by the outer class from external useclass from external use

This is a special relationship and should be used with careThis is a special relationship and should be used with care

Page 55: C0 review core java1

Nested ClassesNested Classes

A nested class produces a separate bytecode fileA nested class produces a separate bytecode file

If a nested class called Inside is declared in an outer class If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced:called Outside, two bytecode files will be produced:

Outside.class

Outside$Inside.class

Nested classes can be declared as static, in which case they Nested classes can be declared as static, in which case they cannot refer to instance variables or methodscannot refer to instance variables or methods

A nonstatic nested class is called an A nonstatic nested class is called an inner classinner class

Page 56: C0 review core java1

InterfacesInterfaces

A Java A Java interfaceinterface is a collection of abstract methods and is a collection of abstract methods and constantsconstants

An An abstract methodabstract method is a method header without a method body is a method header without a method body

An abstract method can be declared using the modifier An abstract method can be declared using the modifier abstractabstract, but because all methods in an interface are , but because all methods in an interface are abstract, it is usually left offabstract, it is usually left off

An interface is used to formally define a set of methods that a An interface is used to formally define a set of methods that a class will implementclass will implement

Page 57: C0 review core java1

InterfacesInterfaces

public interface Doable{ public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num);}

interface is a reserved wordinterface is a reserved wordNone of the methods in anNone of the methods in an

interface are giveninterface are givena definition (body)a definition (body)

A semicolon immediatelyA semicolon immediatelyfollows each method headerfollows each method header

Page 58: C0 review core java1

InterfacesInterfaces

An interface cannot be instantiatedAn interface cannot be instantiated

Methods in an interface have public visibility by defaultMethods in an interface have public visibility by default

A class formally implements an interface byA class formally implements an interface by stating so in the class headerstating so in the class header providing implementations for each abstract method in the providing implementations for each abstract method in the

interfaceinterface

If a class asserts that it implements an interface, it must define If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will produce errors.all methods in the interface or the compiler will produce errors.

Page 59: C0 review core java1

InterfacesInterfaces

public class CanDo implements Doable{ public void doThis () { // whatever }

public void doThat () { // whatever }

// etc.}

implements is aimplements is areserved wordreserved word

Each method listedEach method listedin Doable isin Doable is

given a definitiongiven a definition

Page 60: C0 review core java1

InterfacesInterfaces

A class that implements an interface can implement other A class that implements an interface can implement other methods as wellmethods as well

See See Speaker.java Speaker.java (page 236)(page 236) See See Philosopher.java Philosopher.java (page 237)(page 237) See See Dog.java Dog.java (page 238)(page 238)

A class can implement multiple interfacesA class can implement multiple interfaces The interfaces are listed in the implements clause, separated The interfaces are listed in the implements clause, separated

by commasby commas The class must implement all methods in all interfaces listed in The class must implement all methods in all interfaces listed in

the headerthe header

Page 61: C0 review core java1

Polymorphism via InterfacesPolymorphism via Interfaces

An interface name can be used as the type of an object An interface name can be used as the type of an object reference variablereference variable

Doable obj;

The The objobj reference can be used to point to any object of any reference can be used to point to any object of any class that implements the class that implements the DoableDoable interface interface

The version of The version of doThisdoThis that the following line invokes depends that the following line invokes depends on the type of object that on the type of object that objobj is referring to: is referring to:

obj.doThis();

Page 62: C0 review core java1

Polymorphism via InterfacesPolymorphism via Interfaces That reference is That reference is polymorphicpolymorphic, which can be defined as "having , which can be defined as "having

many forms"many forms"

That line of code might execute different methods at different That line of code might execute different methods at different times if the object that times if the object that objobj points to changes points to changes

See Talking.java (page 240)See Talking.java (page 240)

Note that polymorphic references must be resolved at run time; Note that polymorphic references must be resolved at run time; this is called this is called dynamic bindingdynamic binding

Careful use of polymorphic references can lead to elegant, Careful use of polymorphic references can lead to elegant, robust software designsrobust software designs

Page 63: C0 review core java1
Page 64: C0 review core java1

64

Arrays and VectorsArrays and Vectors

Arrays and vectors are objects that help us organize large Arrays and vectors are objects that help us organize large amounts of informationamounts of information

Focuses :Focuses : array declaration and usearray declaration and use arrays of objectsarrays of objects sorting elements in an arraysorting elements in an array multidimensional arraysmultidimensional arrays the the VectorVector class class using arrays to manage graphicsusing arrays to manage graphics

Page 65: C0 review core java1
Page 66: C0 review core java1

66

InheritanceInheritance

Another fundamental object-oriented technique is called Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes inheritance, which enhances software design and promotes reusereuse

Focuses :Focuses : deriving new classesderiving new classes creating class hierarchies creating class hierarchies the the protectedprotected modifier modifier polymorphism via inheritancepolymorphism via inheritance inheritance used in graphical user interfacesinheritance used in graphical user interfaces

Page 67: C0 review core java1

67

InheritanceInheritance InheritanceInheritance allows a software developer to derive a new class allows a software developer to derive a new class

from an existing onefrom an existing one

The existing class is called the The existing class is called the parent class,parent class, or or superclasssuperclass, or , or base classbase class

The derived class is called the The derived class is called the child classchild class or or subclasssubclass..

As the name implies, the child inherits characteristics of the As the name implies, the child inherits characteristics of the parentparent

That is, the child class inherits the methods and data defined That is, the child class inherits the methods and data defined for the parent classfor the parent class

Page 68: C0 review core java1

68

InheritanceInheritance

Inheritance relationships are often shown graphically in a Inheritance relationships are often shown graphically in a class class diagramdiagram, with the arrow pointing to the parent class, with the arrow pointing to the parent class

Inheritance should create an Inheritance should create an is-a relationshipis-a relationship, meaning , meaning the child the child is ais a more specific version of the parent more specific version of the parent

Vehicle

Car

Page 69: C0 review core java1

69

Deriving SubclassesDeriving Subclasses

In Java, we use the reserved word In Java, we use the reserved word extendsextends to establish an to establish an inheritance relationshipinheritance relationship

class Car extends Vehicleclass Car extends Vehicle

{{

// class contents// class contents

}}

See Words.java (page 324)See Words.java (page 324) See Book.java (page 325)See Book.java (page 325) See Dictionary.java (page 326)See Dictionary.java (page 326)

Page 70: C0 review core java1

70

Controlling InheritanceControlling Inheritance

Visibility modifiers determine which class members get Visibility modifiers determine which class members get inherited and which do notinherited and which do not

Variables and methods declared with Variables and methods declared with publicpublic visibility are visibility are inherited, and those with inherited, and those with privateprivate visibility are not visibility are not

But But publicpublic variables violate our goal of encapsulation variables violate our goal of encapsulation

There is a third visibility modifier that helps in inheritance There is a third visibility modifier that helps in inheritance situations: situations: protectedprotected

Page 71: C0 review core java1

71

The The protectedprotected Modifier Modifier

The The protectedprotected visibility modifier allows a member of a base visibility modifier allows a member of a base class to be inherited into the childclass to be inherited into the child

But But protectedprotected visibility provides more encapsulation than visibility provides more encapsulation than publicpublic does does

However, However, protectedprotected visibility is not as tightly encapsulated as visibility is not as tightly encapsulated as privateprivate visibility visibility

The details of each modifier are given in Appendix FThe details of each modifier are given in Appendix F

Page 72: C0 review core java1

72

The The supersuper Reference Reference

Constructors are not inherited, even though they have public Constructors are not inherited, even though they have public visibilityvisibility

Yet we often want to use the parent's constructor to set up the Yet we often want to use the parent's constructor to set up the "parent's part" of the object"parent's part" of the object

The The supersuper reference can be used to refer to the parent class, reference can be used to refer to the parent class, and is often used to invoke the parent's constructorand is often used to invoke the parent's constructor

See Words2.java (page 328)See Words2.java (page 328) See Book2.java (page 329)See Book2.java (page 329) See Dictionary2.java (page 330)See Dictionary2.java (page 330)

Page 73: C0 review core java1

Single vs. Multiple InheritanceSingle vs. Multiple Inheritance

Java supports Java supports single inheritancesingle inheritance, meaning that a derived class , meaning that a derived class can have only one parent classcan have only one parent class

Multiple inheritanceMultiple inheritance allows a class to be derived from two or allows a class to be derived from two or more classes, inheriting the members of all parentsmore classes, inheriting the members of all parents

Collisions, such as the same variable name in two parents, Collisions, such as the same variable name in two parents, have to be resolvedhave to be resolved

In most cases, the use of interfaces gives us the best aspects In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overheadof multiple inheritance without the overhead

Page 74: C0 review core java1

74

Overriding MethodsOverriding Methods

A child class can A child class can overrideoverride the definition of an inherited method the definition of an inherited method in favor of its ownin favor of its own

That is, a child can redefine a method that it inherits from its That is, a child can redefine a method that it inherits from its parentparent

The new method must have the same signature as the parent's The new method must have the same signature as the parent's method, but can have different code in the bodymethod, but can have different code in the body

The type of the object executing the method determines which The type of the object executing the method determines which version of the method is invokedversion of the method is invoked

Page 75: C0 review core java1

Overriding MethodsOverriding Methods

See Messages.java (page 332)See Messages.java (page 332) See Thought.java (page 333)See Thought.java (page 333) See Advice.java (page 334)See Advice.java (page 334)

Note that a parent method can be explicitly invoked using the Note that a parent method can be explicitly invoked using the supersuper reference reference

If a method is declared with the If a method is declared with the finalfinal modifier, it cannot be modifier, it cannot be overriddenoverridden

The concept of overriding can be applied to data (called The concept of overriding can be applied to data (called shadowing variablesshadowing variables), there is generally no need for it), there is generally no need for it

Page 76: C0 review core java1

76

Overloading vs. OverridingOverloading vs. Overriding Don't confuse the concepts of overloading and overridingDon't confuse the concepts of overloading and overriding

Overloading deals with multiple methods in the same class with Overloading deals with multiple methods in the same class with the same name but different signaturesthe same name but different signatures

Overriding deals with two methods, one in a parent class and Overriding deals with two methods, one in a parent class and one in a child class, that have the same signatureone in a child class, that have the same signature

Overloading lets you define a similar operation in different ways Overloading lets you define a similar operation in different ways for different datafor different data

Overriding lets you define a similar operation in different ways Overriding lets you define a similar operation in different ways for different object typesfor different object types

Page 77: C0 review core java1

77

Class HierarchiesClass Hierarchies

A child class of one parent can be the parent of another child, A child class of one parent can be the parent of another child, forming forming class hierarchiesclass hierarchies

Business

RetailBusiness ServiceBusiness

KMart Macys Kinkos

Page 78: C0 review core java1

78

Class HierarchiesClass Hierarchies

Two children of the same parent are called Two children of the same parent are called siblingssiblings

Good class design puts all common features as high in the Good class design puts all common features as high in the hierarchy as is reasonablehierarchy as is reasonable

An inherited member is continually passed down the lineAn inherited member is continually passed down the line

Class hierarchies often have to be extended and modified to Class hierarchies often have to be extended and modified to keep up with changing needskeep up with changing needs

There is no single class hierarchy that is appropriate for all There is no single class hierarchy that is appropriate for all situationssituations

Page 79: C0 review core java1

79

The The ObjectObject Class Class

A class called A class called ObjectObject is defined in the is defined in the java.langjava.lang package of package of the Java standard class librarythe Java standard class library

All classes are derived from the All classes are derived from the ObjectObject class class

If a class is not explicitly defined to be the child of an existing If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the class, it is assumed to be the child of the ObjectObject class class

The The ObjectObject class is therefore the ultimate root of all class class is therefore the ultimate root of all class hierarchieshierarchies

Page 80: C0 review core java1

The The ObjectObject Class Class

The The ObjectObject class contains a few useful methods, which are class contains a few useful methods, which are inherited by all classesinherited by all classes

For example, the For example, the toStringtoString method is defined in the method is defined in the ObjectObject classclass

Every time we have defined Every time we have defined toStringtoString, we have actually been , we have actually been overriding itoverriding it

The The toStringtoString method in the method in the ObjectObject class is defined to return class is defined to return a string that contains the name of the object’s class and a hash a string that contains the name of the object’s class and a hash valuevalue

Page 81: C0 review core java1

The The ObjectObject Class Class That’s why the That’s why the printlnprintln method can call method can call toStringtoString for any for any

object that is passed to it – all objects are guaranteed to have a object that is passed to it – all objects are guaranteed to have a toStringtoString method via inheritance method via inheritance

See Academia.java (page 339)See Academia.java (page 339) See Student.java (page 340)See Student.java (page 340) See GradStudent.java (page 341)See GradStudent.java (page 341)

The equals method of the Object class determines if two The equals method of the Object class determines if two references are aliasesreferences are aliases

You may choose to override You may choose to override equalsequals to define equality in some to define equality in some other way other way

Page 82: C0 review core java1

Abstract ClassesAbstract Classes

An abstract class is a placeholder in a class hierarchy that An abstract class is a placeholder in a class hierarchy that represents a generic conceptrepresents a generic concept

An abstract class cannot be instantiatedAn abstract class cannot be instantiated

We use the modifier We use the modifier abstractabstract on the class header to declare on the class header to declare a class as abstracta class as abstract

An abstract class often contains abstract methods (like an An abstract class often contains abstract methods (like an interface does), though it doesn’t have tointerface does), though it doesn’t have to

Page 83: C0 review core java1

Abstract ClassesAbstract Classes

The child of an abstract class must override the abstract The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstractmethods of the parent, or it too will be considered abstract

An abstract method cannot be defined as final (because it must An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet)be overridden) or static (because it has no definition yet)

The use of abstract classes is a design decision; it helps us The use of abstract classes is a design decision; it helps us establish common elements in a class that is to general to establish common elements in a class that is to general to instantiateinstantiate

Page 84: C0 review core java1

84

References and InheritanceReferences and Inheritance

An object reference can refer to an object of its class, or to an An object reference can refer to an object of its class, or to an object of any class related to it by inheritanceobject of any class related to it by inheritance

For example, if the For example, if the HolidayHoliday class is used to derive a child class is used to derive a child class called class called ChristmasChristmas, then a , then a HolidayHoliday reference could reference could actually be used to point to a actually be used to point to a ChristmasChristmas object object

Holiday

Christmas

Holiday day;day = new Christmas();

Page 85: C0 review core java1

85

References and InheritanceReferences and Inheritance

Assigning a predecessor object to an ancestor reference is Assigning a predecessor object to an ancestor reference is considered to be a widening conversion, and can be performed considered to be a widening conversion, and can be performed by simple assignmentby simple assignment

Assigning an ancestor object to a predecessor reference can Assigning an ancestor object to a predecessor reference can also be done, but it is considered to be a narrowing conversion also be done, but it is considered to be a narrowing conversion and must be done with a castand must be done with a cast

The widening conversion is the most usefulThe widening conversion is the most useful

Page 86: C0 review core java1

86

Polymorphism via InheritancePolymorphism via Inheritance

We saw in Chapter 5 how an interface can be used to create a We saw in Chapter 5 how an interface can be used to create a polymorphic referencepolymorphic reference

Recall that a polymorphic reference is one which can refer to Recall that a polymorphic reference is one which can refer to different types of objects at different timesdifferent types of objects at different times

Inheritance can also be used as a basis of polymorphismInheritance can also be used as a basis of polymorphism

An object reference can refer to one object at one time, then it An object reference can refer to one object at one time, then it can be changed to refer to another object (related by can be changed to refer to another object (related by inheritance) at another timeinheritance) at another time

Page 87: C0 review core java1

Polymorphism via InheritancePolymorphism via Inheritance

Suppose the Suppose the HolidayHoliday class has a method called class has a method called celebratecelebrate, , and the and the ChristmasChristmas class overrode it class overrode it

Now consider the following invocation:Now consider the following invocation:

day.celebrate();

If If dayday refers to a refers to a HolidayHoliday object, it invokes the object, it invokes the HolidayHoliday version of version of celebratecelebrate; if it refers to a ; if it refers to a ChristmasChristmas object, it object, it invokes the invokes the ChristmasChristmas version version

Page 88: C0 review core java1

88

Polymorphism via InheritancePolymorphism via Inheritance

It is the type of the object being referenced, not the reference It is the type of the object being referenced, not the reference type, that determines which method is invokedtype, that determines which method is invoked

Note that, if an invocation is in a loop, the exact same line of Note that, if an invocation is in a loop, the exact same line of code could execute different methods at different timescode could execute different methods at different times

Polymorphic references are therefore resolved at run-time, not Polymorphic references are therefore resolved at run-time, not during compilationduring compilation

Page 89: C0 review core java1

Polymorphism via InheritancePolymorphism via Inheritance

Consider the following class hierarchy:Consider the following class hierarchy:

StaffMember

Volunteer Employee

Executive Hourly

Page 90: C0 review core java1

Polymorphism via InheritancePolymorphism via Inheritance

Now consider the task of paying all employeesNow consider the task of paying all employees

See Firm.java (page 345)See Firm.java (page 345) See Staff.java (page 346)See Staff.java (page 346) See StaffMember.java (page 348)See StaffMember.java (page 348) See Volunteer.java (page 349)See Volunteer.java (page 349) See Employee.java (page 351)See Employee.java (page 351) See Executive.java (page 352)See Executive.java (page 352) See Hourly.java (page 353)See Hourly.java (page 353)

Page 91: C0 review core java1

91

Indirect AccessIndirect Access

An inherited member can be referenced directly by name in the An inherited member can be referenced directly by name in the child class, as if it were declared in the child classchild class, as if it were declared in the child class

But even if a method or variable is not inherited by a child, it But even if a method or variable is not inherited by a child, it can still be accessed indirectly through parent methodscan still be accessed indirectly through parent methods

See FoodAnalysis.java (page 355)See FoodAnalysis.java (page 355) See FoodItem.java (page 356)See FoodItem.java (page 356) See Pizza.java (page 357)See Pizza.java (page 357)

Page 92: C0 review core java1

Interface HierarchiesInterface Hierarchies

Inheritance can be applied to interfaces as well as classesInheritance can be applied to interfaces as well as classes

One interface can be used as the parent of anotherOne interface can be used as the parent of another

The child interface inherits all abstract methods of the parentThe child interface inherits all abstract methods of the parent

A class implementing the child interface must define all A class implementing the child interface must define all methods from both the parent and child interfacesmethods from both the parent and child interfaces

Note that class hierarchies and interface hierarchies are distinct Note that class hierarchies and interface hierarchies are distinct (the do not overlap)(the do not overlap)

Page 93: C0 review core java1
Page 94: C0 review core java1

94

Exceptions and I/O StreamsExceptions and I/O Streams

We can now further explore two related topics: exceptions and We can now further explore two related topics: exceptions and input / output streamsinput / output streams

Focuses :Focuses : the try-catch statementthe try-catch statement exception propagationexception propagation creating and throwing exceptionscreating and throwing exceptions types of I/O streamstypes of I/O streams Keyboard class processingKeyboard class processing reading and writing text filesreading and writing text files object serializationobject serialization

Page 95: C0 review core java1
Page 96: C0 review core java1

96

Graphical User InterfacesGraphical User Interfaces

We can now explore the creation of graphical user interfaces in We can now explore the creation of graphical user interfaces in more detailmore detail

Focuses :Focuses : GUI infrastructureGUI infrastructure containerscontainers using graphics in applicationsusing graphics in applications Swing componentsSwing components layout managerslayout managers

Page 97: C0 review core java1
Page 98: C0 review core java1

98

Program DevelopmentProgram Development

The creation of software involves four basic activities:The creation of software involves four basic activities:

establishing the requirementsestablishing the requirements creating a designcreating a design implementing the codeimplementing the code testing the implementationtesting the implementation

The development process is much more involved than this, but The development process is much more involved than this, but these basic steps are a good starting pointthese basic steps are a good starting point

Page 99: C0 review core java1
Page 100: C0 review core java1

The major concepts of OOPThe major concepts of OOP

AbstractionAbstraction – – an abstraction deals with the outer perception an abstraction deals with the outer perception of an object. It states the characteristics of an object of an object. It states the characteristics of an object without any focus on its actual implementation.without any focus on its actual implementation.

EncapsulationEncapsulation – – ensures that private object data is only ensures that private object data is only accessible internally. Other objects should only access its accessible internally. Other objects should only access its information using available methods. The Java language information using available methods. The Java language uses the class construct to achieve this, as do many other uses the class construct to achieve this, as do many other languages.languages.

InheritanceInheritance – – one class’ features may be inherited by one class’ features may be inherited by another class. By using inheritance constructs, like another class. By using inheritance constructs, like extends extends in Java, the same code does not need to be in Java, the same code does not need to be duplicated in order for the child to inherit the parent’s duplicated in order for the child to inherit the parent’s functionality. Inheritance leads to a class hierarchy.functionality. Inheritance leads to a class hierarchy.

Page 101: C0 review core java1

The major concepts of OOPThe major concepts of OOP

PolymorphismPolymorphism – – the same method may have different the same method may have different behaviour on different type of input objects. This can be behaviour on different type of input objects. This can be achieved using achieved using method overloadingmethod overloading, i.e. defining the same , i.e. defining the same method several times for different situations. The methods method several times for different situations. The methods may have different implementations.may have different implementations.

ModularityModularity – – an application should be built by developing an application should be built by developing modular, reusable classes.modular, reusable classes.

ReusabilityReusability – – by making components generic and modular, by making components generic and modular, it is easier to reuse components. This holds for both it is easier to reuse components. This holds for both individual objects as well as larger software libraries, individual objects as well as larger software libraries, creating a big opportunity to save resources.creating a big opportunity to save resources.