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

Slides:



Advertisements
Similar presentations
Programming With Java ICS 201 University Of Ha’il1 Chapter 8 Abstract Class.
Advertisements

Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Inheritance Deitel &Deitel Java SE 8.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Abstract Classes. Lecture Objectives To learn about abstract classes To understand how to inherit abstract classes To understand how to override abstract.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Java™ How to Program, 9/e Presented by: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e Presented by: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Object Oriented Programming using Java - Polymorphism
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
Java™ How to Program, 9/e Presented by: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Java SE 8 for Programmers, Third Edition
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces An interface is like an extreme case of an abstract class – However, an interface is not a class – It is a type that can be satisfied by any.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
Inheritance & Method Overriding BCIS 3680 Enterprise Programming.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Object-Oriented Programming: Polymorphism
Inheritance and Polymorphism
Object-Oriented Programming: Polymorphism
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming: Interface
Object-Oriented Programming: Polymorphism
Chapter 9 Object-Oriented Programming: Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Fundaments of Game Design
Abstract Classes and Interfaces
Presentation transcript:

Java SE 8 for Programmers, Third Edition Advanced Java Programming

Contents I  Multidimensional Arrays  Introduction to Collections and Class ArrayList  Object-Oriented Programming(cont’d) Interfaces final Methods and Classes Creating and Using Interfaces Interface Enhancements Exception Handling

Contents II  Swing 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

Creating and Using Interfaces  Let the company has to perform several accounting operations in a single accounts payable application  to 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 earnings For an invoice, the payment refers to the total cost of the goods listed on the invoice.

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.

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.

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.

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.

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.

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.

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 polymorphically  objects 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.

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.

Interfaces vs. Abstract Classes  An interface is often used in place of an abstract class when there’s no default implementation to inherit  No 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.

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

 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

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

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 object  Tis is the case for any object of a class that implements Serializable

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.

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.

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.

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

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

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

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.

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

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

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

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 }

Employee abstract superclass that implements Payable public String getSocialSecurityNumber() // return social security number { return socialSecurityNumber; } // return String representation of Employee 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

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.

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"); this.weeklySalary = weeklySalary; }

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 public double getPaymentAmount() { return getWeeklySalary(); } // return String representation of SalariedEmployee public String toString() { return String.format("salaried employee: %s%n%s: $%,.2f", super.toString(), "weekly salary", getWeeklySalary()); } } // end class SalariedEmployee

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.

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 Invoice is a Payable SalariedEmployee is an EmpEmployee is a Payable  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 Payable  All 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.

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.

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, ); payableObjects[1] = new Invoice("56789", "tire", 4, 79.95); payableObjects[2] = new SalariedEmployee("John", "Smith", " ", ); payableObjects[3] = new SalariedEmployee("Lisa", "Barnes", " ", ); 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 amount System.out.printf("%n%s %n%s: $%,.2f%n", currentPayable.toString(), // could invoke implicitly "paymentdue", currentPayable.getPaymentAmount()); } } // end main } // end class PayableInterfaceTest

Payable interface test program processing Invoices and Employees polymorphically invoice: part number: (seat) quantity: 2 price per item: $ payment due: $ invoice: part number: (tire) quantity: 4 price per item: $79.95 payment due: $ salaried employee: John Smith social security number: weekly salary: $ payment due: $ salaried employee: Lisa Barnes social security number: weekly salary: $1, payment due: $1,200.00