java se 8 for programmers, third edition advanced java programming

37
Java SE 8 for Programmers, Third Edition Advanced Java Programming

Upload: marcus-conley

Post on 24-Dec-2015

260 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Java SE 8 for Programmers, Third Edition

Advanced Java Programming

Page 2: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Contents IMultidimensional ArraysIntroduction to Collections and Class ArrayListObject-Oriented Programming(cont’d) Interfaces final Methods and Classes Creating and Using Interfaces Interface Enhancements Exception Handling

Page 3: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Contents IISwing GUI Components Simple GUI-Based Input/Output with JOptionPane Overview of Swing Components Displaying Text and Images in a Window Text Fields and an Introduction to Event Handling with Nested Classes Buttons That Maintain State JComboBox; Using an Anonymous Inner Class for Event Handling Mouse Event Handling Adapter Classes JPanel Subclass for Drawing with the Mouse Introduction to Layout Managers

Page 4: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Creating and Using InterfacesLet the company has to perform several

accounting operations in a single accounts payable applicationto calculate the earnings that must be paid to each

employee, the company must also calculate the payment due on each of several invoices (i.e., bills for goods purchased).

to calculate the unrelated things (i.e., employees and invoices), both operations have to do with obtaining some kind of payment amount. For an employee, the payment refers to the employee’s

earningsFor an invoice, the payment refers to the total cost of the

goods listed on the invoice.

Page 5: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Creating and Using Interfaces

Can we calculate such different things as the payments due for employees and invoices in a single application polymorphically?

Does Java offer a capability requiring that unrelated classes implement a set of common methods ( a method that calculates a payment amount)?

Java interfaces offer exactly this capability.

Page 6: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Standardizing Interactions

Interfaces define and standardize the ways in which things such as people and systems can interact with one another.

For example, the controls on a radio serve as an interface between radio users and a radio’s internal components.

The controls allow users to perform only a limited set of operations (e.g., change the station, adjust the volume, choose between AM and FM), and different radios may implement the controls in different ways (e.g., using push buttons, dials, voice commands).

The interface specifies what operations a radio must permit users to perform but does not specify how the operations are performed.

Page 7: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Software Objects Communicate Via Interfaces

A Java interface describes a set of methods that can be called on an object to tell something For example, to perform some task or return some piece

of information. An interface declaration begins with the keyword

interface and contains only constants and abstract methods.

All interface members must be public,Interfaces may not specify any implementation details

For example concrete method declarations and instance variables.

Page 8: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Software Objects Communicate Via Interfaces

All methods declared in an interface are implicitly public abstract methods

All fields in an interface are implicitly public, static and final.

Page 9: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Abstract Methods and Constants of Interfaces

According to the Java Language Specification, it’s proper style to declare an interface’s abstract methods without keywords public and abstract, because they’re redundant in interface-method declarations. An interface’s constants should be declared without keywords public, static and final, because they are redundant.

Page 10: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Using an Interface

To use an interface, a concrete class must specify that it implements the interface and must declare each method in the interface with the signature specified in the interface declaration.

To specify that a class implements an interface, add the implements keyword and the name of the interface to the end of your class declaration’s first line.

A class does not implement all the methods of the interface This class is an abstract class and must be declared

abstract.

Page 11: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Relating Disparate Types

An interface is often used when disparate classes need to share common methods and constants Disparete classes are not related by a class hierarchy

This allows objects of unrelated classes to be processed polymorphicallyobjects of classes that implement the same interface can

respond to the same method calls. We can create an interface that describes the desired

functionality, then implement this interface in any classes that require that functionality.

Page 12: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Using an Interface

Implementing an interface is like signing a contract with the compiler that states,

«I will declare all the methods specified by the interface» or «I will declare my class abstract»Failing to implement any method of an interface

in a concrete class that implements the interface results in a compilation error indicating that the class must be declared abstract.

Page 13: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Interfaces vs. Abstract ClassesAn interface is often used in place of an abstract

class when there’s no default implementation to inheritNo fields and no default method implementations.

Like public abstract classes, interfaces are typically public types.

Like a public class, a public interface must be declared in a file with the same name as the interface and the .java filename extension.

Page 14: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Tagging Interfaces

Tagging interfaces (also called marker interfaces) are empty interfaces that have no methods or constant values.Files, Streams and Object Serialization

They’re used to add is-a relationships to classes. For example, object serialization can convert objects to byte

representations and can convert those byte representations back to objects.

To enable this mechanism to work with your objects, you simply have to mark them as Serializable by adding implements Serializable to the end of your class declaration’s first line.All the objects of your class have the is-a relationship with

Serializable

Page 15: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Sometimes we write the individual fields of a record into a file as text, and read those fields from a file.

When the data is output to disk, certain information can lost,

For example the type of each value. if the value "3" is read from a file, there’s no way to tell

whether it came from an int, a String or a double. We have only data, not type information, on a disk.

Sometimes we want to read an object from or write an object to a file or over a network connection.

Object Serialization

Page 16: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Object Serialization

A serialized object is an object represented as a sequence of bytes It includes the object’s data as well as information about

the object’s type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized

Deserialized is the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Page 17: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Object Serialization

import java.io.Serializable; public class Account implements Serializable Class Account implements interface Serializable

This class allows objects of this class to be serialized and deserialized with ObjectOutputStreams and ObjectInputStreams, respectively.

Interface Serializable is a tagging interface. Such an interface does not contain methods. A class that implements Serializable is tagged as being a

Serializable object. This is important, because an ObjectOutputStream will not

output an object unless it is a Serializable objectTis is the case for any object of a class that implements

Serializable

Page 18: Java SE 8 for Programmers, Third Edition Advanced Java Programming

UML Class Diagram of Interfaces

Payable hierarchy UML class diagram.

The diagram shows the interface and class hierarchy.

The hierarchy begins with interface Payable.

The UML distinguishes an interface from other classes

The UML expresses the relationship between a class and an interface through a relationship known as realization.

A class is said to realize, or implement, the methods of an interface.

Page 19: Java SE 8 for Programmers, Third Edition Advanced Java Programming

UML Class Diagram of Interfaces

Classes Invoice and Employee both represent things for which the company must be able to calculate a payment amount.

Both classes implement the Payable interface, so a program can invoke a method on Invoice objects and Employee objects

This enables the polymorphic processing of Invoices and Employees required for the company’s accounts payable application.

Page 20: Java SE 8 for Programmers, Third Edition Advanced Java Programming

UML Class Diagram of Interfaces

A class diagram models a realization as a dashed arrow with a hollow arrowhead pointing from the implementing class to the interface.

The diagram indicates that classes Invoice and Employee each realize interface Payable.

The class diagram Employee appears in italics, indicating that it’s an abstract class. Concrete class SalariedEmployee extends

Employee, inheriting its superclass’s realization relationship with interface Payable.

Page 21: Java SE 8 for Programmers, Third Edition Advanced Java Programming

A Class Can Extend Only One Other Class But Can Implement Many Interfaces

class Invoice implements interface Payable. Like all classes, class Invoice also implicitly extends Object. Java does not allow subclasses to inherit from more than one superclass, but it allows a class to inherit from one superclass and implement as many interfaces as it needs. To implement more than one interface, use a comma-separated list of interface names after keyword implements in the class declaration

Page 22: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Payable Interface Declaration. // Payable.java. Payable interface declaration. public interface Payable { double getPaymentAmount(); }// calculate payment; no implementation Interface

Payable contains public abstract method getPaymentAmount. Interface methods are always public and abstract, so they do not

need to be declared Interface Payable has only one method, but interfaces can have any

number of methods.Method getPaymentAmount has no parameters, but interface

methods can have parameters. Interfaces may also contain final static constants

Page 23: Java SE 8 for Programmers, Third Edition Advanced Java Programming

// Invoice.java // Invoice class that implements Payable. public class Invoice implements Payable { private final String partNumber; private final String partDescription; private int quantity; private double pricePerItem;public Invoice(String partNumber, String partDescription, int quantity, double pricePerItem) { if (quantity < 0) // validate quantity throw new IllegalArgumentException("Quantity must be >= 0"); if (pricePerItem < 0.0) throw new IllegalArgumentException( "Price per item must be >= 0");

Page 24: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Class Invoice class Invoice to represent a simple invoice that contains

billing information for only one kind of part. The class declares private instance variables partNumber,

partDescription, quantity and pricePerItem that indicate the part number, a description of the part, the quantity of the part ordered and the price per item.

Class Invoice also contains a constructor get and set methods that manipulate the class’s instance variables

Class Invoice also contains a toString method that returns a String representation of an Invoice object.

Methods setQuantity and setPricePerItem ensure that quantity and pricePerItem obtain only nonnegative values.

Page 25: Java SE 8 for Programmers, Third Edition Advanced Java Programming

this.quantity = quantity; this.partNumber = partNumber; this.partDescription = partDescription; this.pricePerItem = pricePerItem; } } // end constructor

public String getPartNumber() // get part number { return partNumber; // should validate }// get description public String getPartDescription() { return partDescription; }

public void setQuantity (int quantity) // set quantity { if (quantity < 0) // validate quantity throw new IllegalArgumentException("Quantity must be >= 0"); this.quantity = quantity; } // get quantity public int getQuantity() { return quantity; }

Page 26: Java SE 8 for Programmers, Third Edition Advanced Java Programming

public void setPricePerItem(double pricePerItem) // set price per item { if (pricePerItem < 0.0) // validate pricePerIte throw new IllegalArgumentException( "Price per item must be >= 0"); this.pricePerItem = pricePerItem; }

public double getPricePerItem() // get price per item { return pricePerItem; }

// return String representation of Invoice object @Override public String toString() { return String.format("%s: %n%s: %s (%s) %n%s: %d %n%s: $%,.2f", "invoice", "part number", getPartNumber(), getPartDescription(), "quantity", getQuantity(), "price per item", getPricePerItem()); }

Page 27: Java SE 8 for Programmers, Third Edition Advanced Java Programming

// method required to carry out contract with interface Payable @Override public double getPaymentAmount() { return getQuantity() * getPricePerItem(); // calculate total cost } } // end of the class

Page 28: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Modifying Class Employee to Implement Interface Payable

public abstract class Employee implements Payable { private final String firstName; private final String lastName; private final String socialSecurityNumber;

public Employee(String firstName, String lastName, String socialSecurityNumber) { this.firstName = firstName; this.lastName = lastName; this.socialSecurityNumber = socialSecurityNumber; }

public String getFirstName() // return first name { return firstName; }

public String getLastName() // return last name{ return lastName }

Page 29: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Employee abstract superclass that implements Payable

public String getSocialSecurityNumber() // return social security number { return socialSecurityNumber; }

// return String representation of Employee object @Override public String toString() { return String.format("%s %s%nsocial security number: %s", getFirstName(), getLastName(), getSocialSecurityNumber()); }

// Note: We do not implement Payable method getPaymentAmount here

// this class must be declared abstract to avoid a compilation error. } // end abstract class Employee

Page 30: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Employee abstract superclass that implements Payable

When a class implements an interface, it makes a contract with the compiler stating either that the class will implement each method in the interface or the class will be declared abstract.

Because class Employee does not provide a getPaymentAmount method, the class must be declared abstract.

Any concrete subclass of the abstract class must implement the interface methods to fulfill the superclass’s contract with the compiler.

If the subclass does not do so, it too must be declared abstract. Each direct Employee subclass inherits the superclass’s contract to

implement method getPaymentAmount and thus must implement this method to become a concrete class for which objects can be instantiated.

A class that extends one of Employee’s concrete subclasses will inherit an implementation of getPaymentAmount and thus will also be a concrete class.

Page 31: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Modifying Class SalariedEmployee for Use in the Payable Hierarchy

// SalariedEmployee.java // SalariedEmployee class that implements interface Payable. // method getPaymentAmount. public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee(String firstName, String lastName, String socialSecurityNumber, double weeklySalary) { super(firstName, lastName, socialSecurityNumber); if (weeklySalary < 0.0 throw new IllegalArgumentException( "Weekly salary must be >= 0.0"); this.weeklySalary = weeklySalary; }

Page 32: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Modifying Class SalariedEmployee for Use in the Payable Hierarchy

public void setWeeklySalary(double weeklySalary) // set salary { if (weeklySalary < 0.0) throw new IllegalArgumentException( "Weekly salary must be >= 0.0"); this.weeklySalary = weeklySalary; }public double getWeeklySalary() // return salary { return weeklySalary; } // calculate earnings; implement interface Payable method that was // abstract in superclass Employee @Override public double getPaymentAmount() { return getWeeklySalary(); } // return String representation of SalariedEmployee object @Override public String toString() { return String.format("salaried employee: %s%n%s: $%,.2f", super.toString(), "weekly salary", getWeeklySalary()); } } // end class SalariedEmployee

Page 33: Java SE 8 for Programmers, Third Edition Advanced Java Programming

is-a relationship Explanation When a class implements an interface, the same is-a relationship

provided by inheritance applies. Class Employee implements Payable, so we can say that an

Employee is a Payable. In fact, objects of any classes that extend Employee are also

Payable objects. SalariedEmployee objects, for instance, are Payable objects. Objects of any subclasses of the class that implements the

interface can also be thought of as objects of the interface type. we can assign the reference of a SalariedEmployee object to a superclass

Employee variable, we can assign the reference of a SalariedEmployee object to an interface

Payable variable. Invoice implements Payable, so an Invoice object also is a Payable

object, we can assign the reference of an Invoice object to a Payable variable.

Page 34: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Using Interface Payable to Process Invoices and Employees Polymorphically

PayableInterfaceTest illustrates that interface Payable can be used to process a set of Invoices and Employees polymorphically in a single application.

When payableObjects is declared , an array of four Payable variables is assigned These assignments are allowed because an Invoice is a Payable, a

SalariedEmployee is an Employee and an Employee is a Payable.

The enhanced for statement is used to polymorphically process each Payable object in payableObjects, printing the object as a String, along with the payment amount due.

Method toString is invoked via a Payable interface reference, even though toString is not declared in interface PayableAll references (including those of interface types) refer to objects that

extend Object and therefore have a toString method. Method toString also can be invoked implicitly here.

Page 35: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Using Interface Payable to Process Invoices and Employees Polymorphically

Payable method getPaymentAmount is invoked to obtain the payment amount for each object in payable Objects, regardless of the actual type of the object.

The output reveals that each of the method calls invokes the appropriate class’s implementation of methods toString and getPaymentAmount.

For instance, when currentPayable refers to an Invoice during the first iteration of the for loop, class Invoice’s toString and getPaymentAmount execute.

Page 36: Java SE 8 for Programmers, Third Edition Advanced Java Programming

public class PayableInterfaceTest { public static void main(String[] args) { // create four-element Payable array Payable[] payableObjects = new Payable[4]; // populate array with objects that implement Payable payableObjects[0] = new Invoice("01234", "seat", 2, 375.00); payableObjects[1] = new Invoice("56789", "tire", 4, 79.95); payableObjects[2] = new SalariedEmployee("John", "Smith", "111-11-1111", 800.00);payableObjects[3] = new SalariedEmployee("Lisa", "Barnes", "888-88-8888", 1200.00); System.out.println( "Invoices and Employees processed polymorphically:"); // generically process each element in array payableObjects for (Payable currentPayable : payableObjects) { // output currentPayable and its appropriate payment amountSystem.out.printf("%n%s %n%s: $%,.2f%n", currentPayable.toString(), // could invoke implicitly "paymentdue" , currentPayable.getPaymentAmount()); } } // end main } // end class PayableInterfaceTest

Page 37: Java SE 8 for Programmers, Third Edition Advanced Java Programming

Payable interface test program processing Invoices and Employees polymorphically

invoice: part number: 01234 (seat) quantity: 2 price per item: $375.00 payment due: $750.00

invoice: part number: 56789 (tire) quantity: 4 price per item: $79.95 payment due: $319.80

salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 payment due: $800.00

salaried employee: Lisa Barnes social security number: 888-88-8888 weekly salary: $1,200.00 payment due: $1,200.00