murach’s java se 6, c7© 2007, mike murach & associates, inc.slide 1

50
Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 1 C hapter7 How to w ork w ith interfaces

Upload: agatha-blankenship

Post on 22-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 1

Chapter 7

How to work with interfaces

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 2

Objectives

Applied

Given the specifications for an application that uses inheritance, create the required classes.

Given the specifications for an abstract class or method, write the code for the class and the class that inherits it.

Given the specifications for a final class, method, or parameter, write the code for the class and the class that inherits it.

Write the code necessary for a class to override the equals method of the Object class so you can test two objects created from that class for equality based on the data they contain.

Given the Java code for an application that uses any of the language elements presented in this chapter, explain what each statement in the application does.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 3

Objectives (continued)

Knowledge

In general, explain how inheritance works.

Explain what it means for a subclass to extend a superclass.

Explain how inheritance is used within the Java API classes.

Explain why methods such as toString and equals are available to all objects and when you might override these methods.

Describe two ways that you can use inheritance in your applications.

Describe the accessibility that’s provided by the access modifiers you can use for the members of a class.

Explain what polymorphism is and how it works.

Describe two ways that you can get information about an object’s type.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 4

Objectives (continued) Explain when it’s necessary to use explicit casting when working

with objects created from derived classes.

Explain how abstract classes and methods work.

Explain how final classes, methods, and parameters work.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 5

How inheritance works

Superclass

murach.presentation.ProductFrame

void actionPerformed(ActionEvent e)void keyPressed(KeyEvent e)

setTitle("Product");setLocation(10, 10);setSize(200, 200);setResizable(false);setDefaultCloseOperation(EXIT_ON_CLOSE)

Subclass

Code that usesinherited fields andmethods

New methods

Public fields andmethods

javax.swing.JFrame

HIDE_ON_CLOSEEXIT_ON_CLOSE

void setTitle(String title)void setLocation(int x, int y)void setSize(int h, int w)void setResizable(boolean b)void setDefaultCloseOperation(int i)

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 6

Inheritance concepts Inheritance lets you create a new class based on an existing class.

The new class inherits the fields, constructors, and methods of the existing class.

A class that inherits from an existing class is called a derived class, child class, or subclass.

A class that another class inherits is called a base class, parent class, or superclass.

A subclass can extend the superclass by adding new fields, constructors, and methods to the superclass.

A subclass can override a method from the superclass with its own version of the method.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 7

The inheritance hierarchy for Swing forms and controls

Component

Container

java.awt

Object

java.lang javax.swing

Window

Frame

JComponent

JFrame

Swing classes forbuttons, labels, textboxes, etc.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 8

How the Java API uses inheritance The Java API uses inheritance extensively in its own classes, so

you often need to know what the inheritance hierarchy is as you use these classes. Examples:

All classes ultimately inherit the Object class in the java.lang package.

All Swing classes, which are stored in the javax.swing package, inherit the Component and Container classes in the java.awt package. This package contains the Abstract Windows Toolkit (AWT) classes.

A class can use the fields and methods of any of its superclasses.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 9

The Object class java.lang.Object

How the Object class works The Object class in the java.lang package is the superclass for all

classes. As a result, its methods are available to all classes.

The hash code for an object is a hexadecimal number that identifies the object’s location in memory.

When creating classes, it’s a common practice to override the toString and equals methods so they work appropriately for each class.

In general, you don’t need to override the finalize method for an object. That’s because the garbage collector automatically reclaims the memory of an object whenever it needs to and before it does that, it calls the finalize method of the object.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 10

Methods of the Object class

Method Description

toString() Returns a String object containing the class name, an @ symbol, and the object’s hash code.

equals(Object) Returns true (boolean) if this object points to the same space in memory as the specified object. Otherwise, it returns false, even if both objects contain the same data.

getClass() Returns a Class object that represents the type of this object.

clone() Returns a copy of this object as an Object object (the Cloneable interface must be implemented).

hashCode() Returns the hash code (int) for this object.

finalize() Called by the garbage collector when it determines that there are no more references to the object.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 11

Business classes for a Product Maintenance application

Product

void setCode(String c)String getCode()void setDescription(String d)String getDescription()void setPrice(double p)double getPrice()String getFormattedPrice()String toString()

SoftwareBook

void setCode(String c)String getCode()void setDescription(String d)String getDescription()void setPrice(double p)double getPrice()String getFormattedPrice()String toString()

void setAuthor(String a)String getAuthor()

void setCode(String c)String getCode()void setDescription(String d)String getDescription()void setPrice(double p)double getPrice()String getFormattedPrice()String toString()

void setVersion(String v)String getVersion()

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 12

How to use inheritance in your applications You can use inheritance in your applications to create generic

superclasses that implement common elements of related subclasses.

It’s also common to create classes that inherit from classes that are defined by the Java API.

When you inherit a class, you can use the subclass whenever an instance of the superclass is called for.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 13

Access modifiers

Keyword Description

private Available within the current class.

public Available to classes in all packages.

protected Available to classes in the same package and to subclasses.

no keyword coded Available to classes in the same package.

How to use access modifiers in a superclass Access modifiers specify the accessibility of the members declared

by a class.

A subclass can access the public and protected members of its superclass, but not the private members.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 14

The code for the Product superclass import java.text.NumberFormat; public class Product { private String code; private String description; private double price; protected static int count = 0; // a protected static variable public Product() { code = ""; description = ""; price = 0; } // get and set accessors for the code, description, and price // instance variables

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 15

The code for the Product superclass (continued) public String toString() // override the toString method { String message = "Code: " + code + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; return message; } public static int getCount() // create public access for the { // count variable return count; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 16

The syntax for creating subclasses To declare a subclass public class SubclassName extends SuperClassName{}

To call a superclass constructor super(argumentList)

To call a superclass method super.methodName(argumentList)

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 17

How to create a subclass You can directly access fields that have public or protected access

in the superclass.

You can extend the superclass by adding new fields, constructors, and methods.

You can override methods in the superclass by coding methods that have the same signatures.

You use the super keyword to call a constructor or method of the superclass. If necessary, you can call constructors or methods that pass arguments to the superclass.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 18

The code for a Book subclass public class Book extends Product { private String author; public Book() { super(); // call constructor of Product superclass author = ""; count++; // update the count variable in the Product superclass } public void setAuthor(String author) { this.author = author; } public String getAuthor() { return author; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 19

The code for a Book subclass (continued) public String toString() // override the toString method { String message = super.toString() + // call method of Product superclass "Author: " + author + "\n"; return message; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 20

How polymorphism works Polymorphism is a feature of inheritance that lets you treat objects

of different subclasses that are derived from the same superclass as if they had the type of the superclass.

Example: If Book is a subclass of Product, you can treat a Book object as if it were a Product object.

If you access a method of a superclass object and the method is overridden in the subclasses of that class, polymorphism determines which method is executed based on the object’s type.

Example: If you call the toString method of a Product object, the toString method of the Book class is executed if the object is a Book object.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 21

Polymorphism: 3 versions of the toString method The toString method in the Product superclass public String toString() { return "Code: " + code + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; }

The toString method in the Book subclass public String toString() { return super.toString() + "Author: " + author + "\n"; }

The toString method in the Software subclass public String toString() { return super.toString() + "Version: " + version + "\n"; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 22

Polymorphism: Code that uses the overridden methods Book b = new Book(); b.setCode("java"); b.setDescription("Murach's Beginning Java 2"); b.setPrice(49.50); b.setAuthor("Steelman"); Software s = new Software(); s.setCode("txtp"); s.setDescription("TextPad"); s.setPrice(27.00); s.setVersion("4.7.3"); Product p; p = b; System.out.println(p.toString()); // calls toString from the Book class p = s; System.out.println(p.toString()); // calls toString from the Software class

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 23

The console for the Product application Weclome to the Product Selector Enter product code: java Code: java Description: Murach's Beginning Java 2 Price: $49.50 Author: Andrea Steelman Product count: 1 Continue? (y/n): y Enter product code: txtp Code: txtp Description: TextPad Price: $27.00 Version: 4.7.3 Product count: 2

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 24

The console for the Product application (continued) Continue? (y/n): y Enter product code: xxxx No product matches this product code. Product count: 2 Continue? (y/n):

Description This version of the Product application handles two types of

products: books and software.

The product information that’s displayed depends on the type of product: authors for books, versions for software.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 25

The code for the ProductApp class import java.util.Scanner; public class ProductApp { public static void main(String args[]) { // display a welcome message System.out.println( "Welcome to the Product Selector"); System.out.println(); // perform 1 or more selections Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { System.out.print("Enter product code: "); String productCode = sc.next(); // read the product code sc.nextLine(); // discard any other data entered on the line

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 26

The code for the ProductApp class (continued) // get the Product object Product p = ProductDB.getProduct(productCode); // display the output System.out.println(); if (p != null) System.out.println(p); else System.out.println( "No product matches this product code.\n"); System.out.println( "Product count: " + Product.getCount() + "\n"); // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.nextLine(); System.out.println(); } } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 27

The code for the Product class import java.text.NumberFormat; public class Product { private String code; private String description; private double price; protected static int count = 0; public Product() { code = ""; description = ""; price = 0; } public void setCode(String code) { this.code = code; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 28

The code for the Product class (continued) public String getCode() { return code; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public void setPrice(double price) { this.price = price; } public double getPrice() { return price; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 29

The code for the Product class (continued) public String getFormattedPrice() { NumberFormat currency = NumberFormat.getCurrencyInstance(); return currency.format(price); } public String toString() { return "Code: " + code + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; } public static int getCount() { return count; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 30

The code for the Book class public class Book extends Product { private String author; public Book() { super(); author = ""; count++; } public void setAuthor(String author) { this.author = author; } public String getAuthor() { return author; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 31

The code for the Book class (continued) public String toString() { return super.toString() + "Author: " + author + "\n"; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 32

The code for the Software class public class Software extends Product { private String version; public Software() { super(); version = ""; count++; } public void setVersion(String version) { this.version = version; } public String getVersion() { return version; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 33

The code for the Software class (continued) public String toString() { return super.toString() + "Version: " + version + "\n"; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 34

The code for the ProductDB class public class ProductDB { public static Product getProduct(String productCode) { // In a more realistic application, this code would // get the data for the product from a file or // database. For now, this code just uses if/else // statements to return the correct product data. Product p = null; if (productCode.equalsIgnoreCase("java") || productCode.equalsIgnoreCase("jsps") || productCode.equalsIgnoreCase("mcb2")) { Book b = new Book(); if (productCode.equalsIgnoreCase("java")) { b.setCode(productCode); b.setDescription( "Murach's Beginning Java 2");

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 35

The code for the ProductDB class (continued) b.setPrice(49.50); b.setAuthor("Andrea Steelman"); } else if (productCode.equalsIgnoreCase("jsps")) { b.setCode(productCode); b.setDescription( "Murach's Java Servlets and JSP"); b.setPrice(49.50); b.setAuthor("Andrea Steelman"); } else if (productCode.equalsIgnoreCase("mcb2")) { b.setCode(productCode); b.setDescription( "Murach's Mainframe COBOL"); b.setPrice(59.50); b.setAuthor("Mike Murach"); } p = b; // set Product variable equal to // the Book object

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 36

The code for the ProductDB class (continued) } else if (productCode.equalsIgnoreCase("txtp")) { Software s = new Software(); s.setCode("txtp"); s.setDescription("TextPad"); s.setPrice(27.00); s.setVersion("4.7.3"); p = s; // set Product variable equal to // the Software object } return p; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 37

The Class class java.lang.Class

Common method

Method Description

getName() Returns a String object for the name of this Class object.

How to get information about an object’s type Every object has a getClass method that returns a Class object that

corresponds to the object’s type.

You can use the methods of the Class class to obtain information about any object, such as its name.

You can use the instanceof operator to check if an object is an instance of a particular class.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 38

Example 1: Code that displays an object’s type Product p = new Book(); // create a Book object and // assign it to a Product // variable Class c = p.getClass(); // get the Class object // for the product System.out.println("Class name: " + c.getName()); // print the object type

The console Class name: Book

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 39

Example 2: Code that tests an object’s type Product p = new Book(); // create a Book object if (p.getClass().getName().equals("Book")) System.out.println("This is a Book object");

The console This is a Book object

Example 3: An easier way to test an object’s type Product p = new Book(); // create a Book object if (p instanceof Book) System.out.println("This is a Book object");

The console This is a Book object

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 40

How to cast objects Java can implicitly cast a subclass to a superclass. So you can use

a subclass whenever a reference to its superclass is called for.

Example: You can specify a Book object whenever a Product object is expected because Book is a subclass of Product.

You must explicitly cast a superclass object when a reference to one of its subclasses is required.

Example: You must explicitly cast a Product object to Book if a Book object is expected. If the Product object isn’t a valid Book object, a ClassCastException will be thrown.

Casting affects the methods that are available from an object.

Example: If you store a Book object in a Product variable, you can’t call the setAuthor method because it’s defined by the Book class, not the Product class.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 41

Casting examples that use the Product and Book classes Book b = new Book(); b.setCode("java"); b.setDescription("Murach's Beginning Java 2"); b.setAuthor("Andrea Steelman"); b.setPrice(49.50); Product p = b; // cast Book object to a Product object p.setDescription("Test"); // OK - method in Product class //p.setAuthor("Test"); // not OK - method not in Product class b = (Book) p; // cast the Product object back to a Book object b.setAuthor("Test"); // OK - method in Book class Product p2 = new Product(); Book b2 = (Book) p2; // will throw a ClassCastException because // p2 is a Product object not a Book object

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 42

How to compare objects To test if two objects point to the same space in memory, you can

use the equals method of the Object class.

To test if two objects store the same data, you can override the equals method in the subclass so it tests whether all instance variables in the two objects are equal.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 43

How the equals method of the Object class works Example 1: Both variables refer to the same object Product product1 = new Product(); Product product2 = product1; if (product1.equals(product2)) // expression returns true

Example 2: Both variables refer to different objects that store the same data Product product1 = new Product(); Product product2 = new Product(); if (product1.equals(product2)) // expression returns // false

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 44

How to override the equals method of the Object class

Example 1: The equals method of the Product class public boolean equals(Object object) { if (object instanceof Product) { Product product2 = (Product) object; if ( code.equals(product2.getCode()) && description.equals( product2.getDescription()) && price == product2.getPrice() ) return true; } return false; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 45

How to override the equals method of the Object class (continued)

Example 2: The equals method of the LineItem class public boolean equals(Object object) { if (object instanceof LineItem) { LineItem li = (LineItem) object; if ( product.equals(li.getProduct()) && quantity == li.getQuantity() ) return true; } return false; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 46

An abstract Product class public abstract class Product { private String code; private String description; private double price; // regular constructors and methods for instance // variables public String toString() { return "Code: " + code + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; } abstract String getDisplayText(); // an abstract method }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 47

A class that inherits the abstract Product class public class Book extends Product { private String author; // regular constructor and methods for the Book class public String getDisplayText() // implement the abstract method { return super.toString() + "Author: " + author + "\n"; } }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 48

How to work with the abstract keyword An abstract class is a class that can be inherited by other classes

but that you can’t use to create an object.

To declare an abstract class, code the abstract keyword in the class declaration.

An abstract class can contain fields, constructors, and methods just like other superclasses. It can also contain abstract methods.

To create an abstract method, you code the abstract keyword in the method declaration and you omit the method body.

Abstract methods cannot have private access. However, they may have protected or default access (no access modifier).

When a subclass inherits an abstract class, all abstract methods in the abstract class must be overridden in the subclass.

Any class that contains an abstract method must be declared as abstract.

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 49

A final class public final class Book extends Product { // all methods in the class are automatically final }

A final method public final String getVersion() { return version; }

A final parameter public void setVersion(final String version) { // version = "new value"; // not allowed this.version = version; }

Murach’s Java SE 6, C7 © 2007, Mike Murach & Associates, Inc. Slide 50

How to work with the final keyword To prevent a class from being inherited, you can create a final

class.

To prevent subclasses from overriding a method of a superclass, you can create a final method.

To prevent a method from assigning a new value to a parameter, you can create a final parameter.

All methods in a final class are automatically final methods.

Coding the final keyword for classes and methods can result in a minor performance improvement because the compiler doesn’t have to allow for inheritance and polymorphism.