INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects...

35
INF 523Q INF 523Q Chapter 5: Chapter 5: Enhancing Classes Enhancing Classes
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    0

Transcript of INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects...

INF 523QINF 523Q

Chapter 5: Chapter 5: Enhancing ClassesEnhancing Classes

2

Enhancing ClassesEnhancing Classes

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

Chapter 5 focuses on:Chapter 5 focuses on:• 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

3

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 Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an objectdepict a reference graphically as a “pointer” to an object

ChessPiece bishop1 = new ChessPiece();

bishop1

4

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

5

Reference AssignmentReference Assignment

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

bishop2 = bishop1;

Before

bishop1 bishop2

After

bishop1 bishop2

6

AliasesAliases

Two or more references that refer to the same object are Two or more references that refer to the same object are called 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

7

Garbage CollectionGarbage Collection

When an object no longer has any valid references to it, it When an object no longer has any valid references to it, it can no longer be accessed by the programcan no 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 In other languages, the programmer has the responsibility for performing garbage collectionfor performing garbage collection

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 passed in) is stored into the formal parameter (in the method header)method 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

Passing Objects to MethodsPassing Objects to Methods

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

See See Num.java Num.java (page 230)(page 230) See See ParameterTesterParameterTester.java .java (page 228)(page 228) See See ParameterPassingParameterPassing.java .java (page 226)(page 226)

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

Num.javaNum.java //******************************************************************** // Num.java Author: Lewis and Loftus // Represents a single integer as an object. //******************************************************************** class Num { private int value; // Sets up the new Num object, storing an initial value. public Num (int update) { value = update; } // Sets the stored value to the newly specified value. public void setValue (int update) { value = update; } // Returns the stored integer value as a string. public String toString () { return value + ""; } }

ParameterTester.javaParameterTester.java //******************************************************************** // ParameterTester.java Author: Lewis and Loftus // Demonstrates the effects of passing various types of parameters. //********************************************************************

class ParameterTester { // Modifies the parameters, printing their values before and after making the changes. public void changeValues (int f1, Num f2, Num f3) { System.out.println ("Before changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); f1 = 999; f2.setValue(888); f3 = new Num (777); System.out.println ("After changing the values:"); System.out.println ("f1\tf2\tf3"); System.out.println (f1 + "\t" + f2 + "\t" + f3 + "\n"); } }

ParameterPassing.javaParameterPassing.java //****************************************************************** // ParameterPassing.java Author: Lewis and Loftus // Demonstrates the effects of passing various types of parameters. //****************************************************************** class ParameterPassing { // Sets up three variables (one primitive and two objects) to serve as actual parameters // to the changeValues method. Prints their values before and after calling the method. public static void main (String[] args) { ParameterTester tester = new ParameterTester(); int a1 = 111; Num a2 = new Num (222); Num a3 = new Num (333); System.out.println ("Before calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); tester.changeValues (a1, a2, a3); System.out.println ("After calling changeValues:"); System.out.println ("a1\ta2\ta3"); System.out.println (a1 + "\t" + a2 + "\t" + a3 + "\n"); } }

13

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 methods) that can be invoked through the class name rather than through a particular objectrather than through 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 modifier to the method definitionthe method 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 It associates a variable or method with the class rather than an objectan object

14

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

15

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 However, they can reference static variables or local variablesvariables

16

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 If a variable is declared as static, only one copy of the variable existsvariable exists

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

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 Changing the value of a static variable in one object changes it for all others changes it for all others

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

See See MyClassMyClass.java .java (page 234)(page 234) See See CountInstancesCountInstances.java .java (page 233)(page 233)

MyClass.javaMyClass.java //****************************************************************** // MyClass.java Author: Lewis and Loftus // Demonstrates the use of the static modifier. //****************************************************************** class MyClass { private static int count = 0; // Counts the number of instances created. public MyClass () { count++; } // Returns the number of instances of this class that have been created. public static int getCount () { return count; } }

CountInstances.javaCountInstances.java //****************************************************************** // CountInstances.java Author: Lewis and Loftus // Demonstrates the use of the static modifier. //******************************************************************

class CountInstances { // Creates several MyClass objects and prints the number of // objects that were created. public static void main (String[] args) { MyClass obj;

for (int scan=1; scan <= 10; scan++) obj = new MyClass();

System.out.println ("Objects created: " + MyClass.getCount()); } }

Nested ClassesNested Classes

In addition to a class containing data and methods, it can In addition to a class containing data and methods, it can also contain other classesalso contain 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

Nested ClassesNested Classes

A nested class has access to the variables and methods of A nested class has access to the variables and methods of the outer class, even if they are declared privatethe outer 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

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

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 is a method header without a method bodybody

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 An interface is used to formally define a set of methods that a class will implementa class will implement

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

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 If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will define all methods in the interface or the compiler will produce errors.produce errors.

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

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, The interfaces are listed in the implements clause,

separated by commasseparated by commas The class must implement all methods in all interfaces The class must implement all methods in all interfaces

listed in the headerlisted in the header

Speaker.javaSpeaker.java //****************************************************************** // Speaker.java Author: Lewis and Loftus // Demonstrates the declaration of an interface. //******************************************************************

interface Speaker { public void speak (); public void announce (String str); }

Philosopher.javaPhilosopher.java //****************************************************************** // Philosopher.java Author: Lewis and Loftus // Demonstrates the implementation of an interface. //****************************************************************** class Philosopher implements Speaker { private String philosophy; // Establishes this philosopher's philosophy. public Philosopher (String philosophy) { this.philosophy = philosophy; } // Prints this philosophers's philosophy. public void speak () { System.out.println (philosophy); }

Philosopher.java (cont.)Philosopher.java (cont.) // Prints the specified announcement. public void announce (String announcement) { System.out.println (announcement); } // Prints this philosophers's philosophy multiple times. public void pontificate () { for (int count=1; count <= 5; count++) System.out.println (philosophy); } }

Dog.javaDog.java //****************************************************************** // Dog.java Author: Lewis and Loftus // Demonstrates the implementation of an interface. //****************************************************************** class Dog implements Speaker { // Prints this dog's philosophy. public void speak () { System.out.println ("woof"); } // Prints this dog's philosophy and the specified announcement. public void announce (String announcement) { System.out.println ("woof: " + announcement); } }

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 that the following line invokes depends on the type of object that depends on the type of object that objobj is referring to: is referring to:

obj.doThis();

Polymorphism via InterfacesPolymorphism via Interfaces

That reference is That reference is polymorphicpolymorphic, which can be defined as , which can be defined as "having many forms""having many forms"

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

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

Note that polymorphic references must be resolved at run Note that polymorphic references must be resolved at run time; this is called time; 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

Talking.javaTalking.java //****************************************************************** // Talking.java Author: Lewis and Loftus // Demonstrates the use of an interface for polymorphic references. //****************************************************************** class Talking { // Instantiates two objects using an interface reference and invokes one of the // common methods. Then casts the interface reference into a class reference // to invoke its unique method. public static void main (String[] args) { Speaker current; current = new Dog(); current.speak(); current = new Philosopher ("I think, therefore I am."); current.speak(); ((Philosopher) current).pontificate(); } }

InterfacesInterfaces

The Java standard class library contains many interfaces The Java standard class library contains many interfaces that are helpful in certain situationsthat are helpful in certain situations

The The ComparableComparable interface contains an abstract method interface contains an abstract method called called compareTocompareTo, which is used to compare two objects, which is used to compare two objects

The The StringString class implements class implements ComparableComparable which gives which gives us the ability to put strings in alphabetical orderus the ability to put strings in alphabetical order

The The IteratorIterator interface contains methods that allow the interface contains methods that allow the user to move through a collection of objects easilyuser to move through a collection of objects easily