Unformatted Document Excerpt
Coursehero >>
Texas >>
LeTourneau >>
COSC 2103
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
1 0 Object-Oriented Programming: Polymorphism 1 2005 Pearson Education, Inc. All rights reserved. 2 One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. -- John Ronald Reuel Tolkien General propositions do not decide concrete cases. -- Oliver Wendell Holmes A philosopher of imposing stature doesn't think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. -- Alfred North Whitehead Why art thou cast down, O my soul? -- Psalms 42:5 2005 Pearson Education Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn: The concept of polymorphism. To use overridden methods to effect polymorphism. To distinguish between abstract and concrete classes. To declare abstract methods to create abstract classes. How polymorphism makes systems extensible and maintainable. To determine an object's type at execution time. To declare and implement interfaces. 2005 Pearson Education, Inc. All rights reserved. 4 10.1 Introduction 10.2 Polymorphism Examples 10.3 Demonstrating Polymorphic Behavior 10.4 Abstract Classes and Methods 10.5 Case Study: Payroll System Using Polymorphism 10.5.1 Creating Abstract Superclass Em ployee 10.5.2 Creating Concrete Subclass SalariedEm ployee 10.5.3 Creating Concrete Subclass Hourl yEm ployee 10.5.4 Creating Concrete Subclass CommissionEm ployee 10.5.5 Creating Indirect Concrete Subclass BasePlusCommissionEm ployee 10.5.6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting 10.5.7 Summary of the Allowed Assignments Between Superclass and Subclass Variables 10.6 final Methods and Classes 2005 Pearson Education, Inc. All rights reserved. 5 10.7 Case Study: Creating and Using Interfaces 10.7.1 Developing a Payable Hierarchy 10.7.2 Declaring Interface Payable 10.7.3 Creating Class Invoice 10.7.4 Modifying Class Em ployee to Implement Interface Payable 10.7.5 Modifying Class SalariedEm ployee for Use in the Payable Hierarchy 10.7.6 Using Interface Payable to Process Invoices and Em ployees Polymorphically 10.7.7 Declaring Constants with Interfaces 10.7.8 Common Interfaces of the Java API 10.8 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 10.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System 10.10 Wrap-Up 2005 Pearson Education, Inc. All rights reserved. 6 10.1 Introduction Polymorphism Enables "programming in the general" The same invocation can produce "many forms" of results Interfaces Implemented by classes to assign common functionality to possibly unrelated classes 2005 Pearson Education, Inc. All rights reserved. 7 10.2 Polymorphism Examples Polymorphism When a program invokes a method through a superclass variable, the correct subclass version of the method is called, based on the type of the reference stored in the superclass variable The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked Facilitates adding new classes to a system with minimal modifications to the system's code 2005 Pearson Education, Inc. All rights reserved. 8 Software Engineering Observation 10.1 Polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects (as long as the objects belong to the same inheritance hierarchy). 2005 Pearson Education, Inc. All rights reserved. 9 Software Engineering Observation 10.2 Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types. 2005 Pearson Education, Inc. All rights reserved. 10.3 Demonstrating Polymorphic Behavior A superclass reference can be aimed at a subclass object This is possible because a subclass object is a superclass object as well When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called 10 A subclass reference can be aimed at a superclass object only if the object is downcasted 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 10.1: PolymorphismTest.java // Assigning superclass and subclass references to superclass and // subclass variables. public class PolymorphismTest { public static void main( String args[] ) { // assign superclass reference to superclass variable Outline 11 Pol ymor phismT est .java 10 CommissionEmployee3 commissionEmployee = new CommissionEmployee3( 11 "Sue", "Jones", "222222222", 10000, .06 ); 12 13 // assign subclass reference to subclass variable 14 BasePlusCommissionEmployee4 basePlusCommissionEmployee = 15 new BasePlusCommissionEmployee4( 16 "Bob", "Lewis", "333333333", 5000, .04, 300 ); 17 18 // invoke toString on superclass object using superclass variable 19 System.out.printf( "%s %s:\n\n%s\n\n", 20 "Call CommissionEmployee3's toString with superclass reference ", 21 "to superclass object", commissionEmployee.toString() ); 22 23 // invoke toString on subclass object using subclass variable 24 System.out.printf( "%s %s:\n\n%s\n\n", 25 "Call BasePlusCommissionEmployee4's toString with subclass", 26 "reference to subclass object", 27 basePlusCommissionEmployee.toString() ); 28 (1 of 2) Typical reference assignments 2005 Pearson Education, Inc. All rights reserved. 29 // invoke toString on subclass object using superclass variable 30 CommissionEmployee3 commissionEmployee2 = 31 basePlusCommissionEmployee; 32 System.out.printf( "%s %s:\n\n%s\n", 33 "Call BasePlusCommissionEmployee4's toString with superclass", 35 } // end main 36 } // end class PolymorphismTest 12 Assign a reference to a Outline basePlusCommissionEmployee object to a CommissionEmployee3 variable 34 "reference to subclass object", commissionEmployee2.toString() ); Pol ymor phismT est .java Call CommissionEmployee3's toString with superclass reference to superclass Polymorphically call object: commission employee: Sue Jones <a href="/keyword/social-security-number/" >social security number</a> : 222222222 gross sales: 10000.00 commission rate: 0.06 basePlusCommissionEmployee's toString method (2 of 2) Call BasePlusCommissionEmployee4's toString with subclass reference to subclass object: basesalaried commission employee: Bob Lewis <a href="/keyword/social-security-number/" >social security number</a> : 333333333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Call BasePlusCommissionEmployee4's toString with superclass reference to subclass object: basesalaried commission employee: Bob Lewis <a href="/keyword/social-security-number/" >social security number</a> : 333333333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 2005 Pearson Education, Inc. All rights reserved. 13 10.4 Abstract Classes and Methods Abstract classes Classes that are too general to create real objects Used only as abstract superclasses for concrete subclasses and to declare reference variables Many inheritance hierarchies have abstract superclasses occupying the top few levels Keyword abstract Use to declare a class abstract Also use to declare a method abstract Abstract classes normally contain one or more abstract methods All concrete subclasses must override all inherited abstract methods 2005 Pearson Education, Inc. All rights reserved. 10.4 Abstract Classes and Methods (Cont.) Iterator class Traverses all the objects in a collection, such as an array Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchy 14 2005 Pearson Education, Inc. All rights reserved. 15 Software Engineering Observation 10.3 An abstract class declares common attributes and behaviors of the various classes in a class hierarchy. An abstract class typically contains one or more abstract methods that subclasses must override if the subclasses are to be concrete. The instance variables and concrete methods of an abstract class are subject to the normal rules of inheritance. 2005 Pearson Education, Inc. All rights reserved. 16 Common Programming Error 10.1 Attempting to instantiate an object of an abstract class is a compilation error. 2005 Pearson Education, Inc. All rights reserved. 17 Common Programming Error 10.2 Failure to implement a superclass's abstract methods in a subclass is a compilation error unless the subclass is also declared abstract . 2005 Pearson Education, Inc. All rights reserved. 18 Fig. 10.2 | Em ployee hierarchy UML class diagram. 2005 Pearson Education, Inc. All rights reserved. 19 Software Engineering Observation 10.4 A subclass can inherit "interface" or "implementation" from a superclass. Hierarchies designed for im plementation inheritance tend to have their functionality high in the hierarchy--each new subclass inherits one or more methods that were implemented in a superclass, and the subclass uses the superclass implementations. (cont...) 2005 Pearson Education, Inc. All rights reserved. 20 Software Engineering Observation 10.4 Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy--a superclass specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual subclasses override these methods to provide subclass-specific implementations. 2005 Pearson Education, Inc. All rights reserved. 10.5.1 Creating Abstract Superclass Employee abstract superclass Employee earnings is declared abstract No implementation can be given for earnings in the Employee abstract class 21 An array of Employee variables will store references to subclass objects earnings method calls from these variables will call the appropriate version of the earnings method 2005 Pearson Education, Inc. All rights reserved. 22 Fig. 10.3 | Polymorphic interface for the Em ployee hierarchy classes. 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.4: Employee.java // Employee abstract superclass. public abstract class Employee { private String firstName; private String lastName; private String socialSecurityNumber; // threeargument constructor public Employee( String first, String last, String ssn ) { firstName = first; lastName = last; socialSecurityNumber = ssn; } // end threeargument Employee constructor Outline Declare abstract class Employee Attributes common to all employees Em ployee.java 23 (1 of 3) 2005 Pearson Education, Inc. All rights reserved. // set first name public void setFirstName( String first ) { firstName = first; } // end method setFirstName // return first name public String getFirstName() { return firstName; } // end method getFirstName // set last name public void setLastName( String last ) { lastName = last; } // end method setLastName // return last name public String getLastName() { return lastName; } // end method getLastName Outline Em ployee.java 24 (2 of 3) 2005 Pearson Education, Inc. All rights reserved. // set <a href="/keyword/social-security-number/" >social security number</a> public void setSocialSecurityNumber( String ssn ) { socialSecurityNumber = ssn; // should validate } // end method setSocialSecurityNumber // return <a href="/keyword/social-security-number/" >social security number</a> public String getSocialSecurityNumber() { return socialSecurityNumber; } // end method getSocialSecurityNumber // return String representation of Employee object public String toString() { return String.format( "%s %s\n<a href="/keyword/social-security-number/" >social security number</a> : %s", getFirstName(), getLastName(), getSocialSecurityNumber() ); } // end method toString // abstract method overridden by subclasses public abstract double earnings(); // no implementation here } // end abstract class Employee Outline Em ployee.java 25 (3 of 3) abstract method earnings has no implementation 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.5: SalariedEmployee.java // SalariedEmployee class extends Employee. public class SalariedEmployee extends Employee { private double weeklySalary; // fourargument constructor public SalariedEmployee( String first, String last, String ssn, double salary ) Call superclass constructor { super( first, last, ssn ); // pass to Employee constructor setWeeklySalary( salary ); // validate and store salary } // end fourargument SalariedEmployee constructor // set salary public void setWeeklySalary( double salary ) { weeklySalary = salary < 0.0 ? 0.0 : salary; } // end method setWeeklySalary Outline Class SalariedEmployee extends class Employee 26 SalariedEm ployee .java (1 of 2) Call setWeeklySalary method Validate and set weekly salary value 2005 Pearson Education, Inc. All rights reserved. // return salary public double getWeeklySalary() { return weeklySalary; } // end method getWeeklySalary // calculate earnings; override abstract method earnings in Employee public double earnings() { Override earnings method return getWeeklySalary(); so } // end method earnings SalariedEmployee can be // return String representation of SalariedEmployee object public String toString() Override toString { return String.format( "salaried employee: %s\n%s: $%,.2f", super.toString(), "weekly salary", getWeeklySalary() ); } // end method toString } // end class SalariedEmployee Outline 27 SalariedEm ployee .java concrete (2 of 2) method Call superclass's version of toString 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.6: HourlyEmployee.java // HourlyEmployee class extends Employee. public class HourlyEmployee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week Outline Class HourlyEmployee extends class Employee Hourl yEm ployee .java 28 // fiveargument constructor public HourlyEmployee( String first, String last, String ssn, double hourlyWage, double hoursWorked ) Call superclass { super( first, last, ssn ); setWage( hourlyWage ); // validate hourly wage setHours( hoursWorked ); // validate hours worked } // end fiveargument HourlyEmployee constructor // set wage public void setWage( double hourlyWage ) { wage = ( hourlyWage < 0.0 ) ? 0.0 : hourlyWage; } // end method setWage // return wage public double getWage() { return wage; } // end method getWage constructor (1 of 2) Validate and set hourly wage value 2005 Pearson Education, Inc. All rights reserved. // set hours worked public void setHours( double hoursWorked ) { hours = ( ( hoursWorked >= 0.0 ) && ( hoursWorked <= 168.0 ) ) ? hoursWorked : 0.0; } // end method setHours // return hours worked public double getHours() { return hours; } // end method getHours // calculate earnings; override abstract method earnings in Employee public double earnings() { if ( getHours() <= 40 ) // no overtime else return 40 * getWage() + ( gethours() 40 ) * getWage() * 1.5; } // end method earnings // return String representation of HourlyEmployee object Outline Hourl yEm ployee 29 Validate and set hours worked value .java (2 of 2) Override earnings method so HourlyEmployee can be concrete return getWage() * getHours(); Override public String toString() { return String.format( "hourly employee: %s\n%s: $%,.2f; %s: %,.2f", super.toString(), "hourly wage", getWage(), "hours worked", getHours() ); } // end method toString } // end class HourlyEmployee toString method Call superclass's toString method 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.7: CommissionEmployee.java // CommissionEmployee class extends Employee. public class CommissionEmployee extends Employee { private double grossSales; // gross weekly sales private double commissionRate; // commission percentage // fiveargument constructor public CommissionEmployee( String first, String last, String ssn, double sales, double rate ) { super( first, last, ssn ); setGrossSales( sales ); setCommissionRate( rate ); } // end fiveargument CommissionEmployee constructor // set commission rate public void setCommissionRate( double rate ) { commissionRate = ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0; } // end method setCommissionRate Outline Class CommissionEmployee extends class Employee 30 CommissionEm ploy ee.java (1 of 3) Call superclass constructor Validate and set commission rate value 2005 Pearson Education, Inc. All rights reserved. // return commission rate public double getCommissionRate() { return commissionRate; } // end method getCommissionRate // set gross sales amount public void setGrossSales( double sales ) { grossSales = ( sales < 0.0 ) ? 0.0 : sales; } // end method setGrossSales // return gross sales amount public double getGrossSales() { return grossSales; } // end method getGrossSales Outline 31 CommissionEm ploy ee.java (2 of 3) Validate and set the gross sales value 2005 Pearson Education, Inc. All rights reserved. // calculate earnings; override abstract method earnings in Employee public double earnings() { Outline 32 Override earnings return getCommissionRate() * getGrossSales(); method so CommissionEmployee can be concrete } // end method earnings // return String representation of CommissionEmployee object public String toString() { return String.format( "%s: %s\n%s: $%,.2f; %s: %.2f", "commission employee", super.toString(), "gross sales", getGrossSales(), "commission rate", getCommissionRate() ); } // end method toString } // end class CommissionEmployee CommissionEm ploy ee.java Override toString method (3 of 3) Call superclass's toString method 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.8: BasePlusCommissionEmployee.java Class BasePlusCommissionEmployee // BasePlusCommissionEmployee class extends CommissionEmployee. extends class CommissionEmployee Outline 33 public class BasePlusCommissionEmployee extends CommissionEmployee { private double baseSalary; // base salary per week // sixargument constructor public BasePlusCommissionEmployee( String first, String last, String ssn, double sales, double rate, double salary ) { super( first, last, ssn, sales, rate ); BasePlusCommissi onEm ployee.java Call superclass constructor (1 of 2) setBaseSalary( salary ); // validate and store base salary } // end sixargument BasePlusCommissionEmployee constructor // set base salary public void setBaseSalary( double salary ) { baseSalary = ( salary < 0.0 ) ? 0.0 : salary; // nonnegative } // end method setBaseSalary Validate and set base salary value 2005 Pearson Education, Inc. All rights reserved. // return base salary public double getBaseSalary() { return baseSalary; } // end method getBaseSalary // calculate earnings; override method earnings in CommissionEmployee public double earnings() Override earnings { return getBaseSalary() + super.earnings(); } // end method earnings // return String representation of BasePlusCommissionEmployee object public String toString() Override toString { return String.format( "%s %s; %s: $%,.2f", "basesalaried", super.toString(), "base salary", getBaseSalary() ); } // end method toString } // end class BasePlusCommissionEmployee Outline 34 BasePlusCommissi onEm ployee.java method (2 of 2) Call superclass's earnings method method Call superclass's toString method 2005 Pearson Education, Inc. All rights reserved. // Fig. 10.9: PayrollSystemTest.java // Employee hierarchy test program. public class PayrollSystemTest { public static void main( String args[] ) { // create subclass objects SalariedEmployee salariedEmployee = new SalariedEmployee( "John", "Smith", "111111111", 800.00 ); HourlyEmployee hourlyEmployee = new HourlyEmployee( "Karen", "Price", "222222222", 16.75, 40 ); CommissionEmployee commissionEmployee = new CommissionEmployee( "Sue", "Jones", "333333333", 10000, .06 ); BasePlusCommissionEmployee basePlusCommissionEmployee = new BasePlusCommissionEmployee( "Bob", "Lewis", "444444444", 5000, .04, 300 ); System.out.println( "Employees processed individually:\n" ); Outline 35 PayrollSystemT est .java (1 of 5) 2005 Pearson Education, Inc. All rights reserved. System.out.printf( "%s\n%s: $%,.2f\n\n", salariedEmployee, "earned", salariedEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", hourlyEmployee, "earned", hourlyEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", commissionEmployee, "earned", commissionEmployee.earnings() ); System.out.printf( "%s\n%s: $%,.2f\n\n", basePlusCommissionEmployee, "earned", basePlusCommissionEmployee.earnings() ); // create fourelement Employee array Employee employees[] = new Employee[ 4 ]; // initialize array with Employees employees[ 0 ] = salariedEmployee; employees[ 1 ] = hourlyEmployee; employees[ 2 ] = commissionEmployee; employees[ 3 ] = basePlusCommissionEmployee; Outline 36 PayrollSystemT est .java (2 of 5) Assigning subclass objects to supercalss variables System.out.println( "Employees processed polymorphically:\n" ); // generically process each element in array employees for ( Employee currentEmployee : employees ) { System.out.println( currentEmployee ); // invokes toString Implicitly and polymorphically call toString 2005 Pearson Education, Inc. All rights reserved. // determine whether element is a BasePlusCommissionEmployee if ( currentEmployee instanceof BasePlusCommissionEmployee ) { // downcast Employee reference to // BasePlusCommissionEmployee reference BasePlusCommissionEmployee employee = Outline 37 If the currentEmployee variable points to a BasePlusCommissionEmployee object PayrollSystemT est ( BasePlusCommissionEmployee ) currentEmployee; double oldBaseSalary = employee.getBaseSalary(); employee.setBaseSalary( 1.10 * oldBaseSalary ); System.out.printf( employee.getBaseSalary() ); } // end if System.out.printf( } // end for // get type name of each object in employees array for ( int j = 0; j < employees.length; j++ ) System.out.printf( "Employee %d is a %s\n", j, employees[ j ].getClass().getName() ); } // end main } // end class PayrollSystemTest Downcast currentEmployee to a .java BasePlusCommissionEmployee reference (3 of 5) "new base salary with 10%% increase is: $%,.2f\n", Give BasePlusCommissionEmployees a 10% base salary bonus "earned $%,.2f\n\n", currentEmployee.earnings() ); Polymorphically call earnings method Call getClass and getName methods to display each Employee subclass object's class name 2005 Pearson Education, Inc. All rights reserved. Employees processed individually: salaried employee: John Smith <a href="/keyword/social-security-number/" >social security number</a> : 111111111 weekly salary: $800.00 earned: $800.00 hourly employee: Karen Price <a href="/keyword/social-security-number/" >social security number</a> : 222222222 hourly wage: $16.75; hours worked: 40.00 earned: $670.00 commission employee: Sue Jones <a href="/keyword/social-security-number/" >social security number</a> : 333333333 gross sales: $10,000.00; commission rate: 0.06 earned: $600.00 basesalaried commission employee: Bob Lewis <a href="/keyword/social-security-number/" >social security number</a> : 444444444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 earned: $500.00 Outline 38 PayrollSystemT est .java (4 of 5) 2005 Pearson Education, Inc. All rights reserved. Employees processed polymorphically: salaried employee: John Smith <a href="/keyword/social-security-number/" >social security number</a> : 111111111 weekly salary: $800.00 earned $800.00 hourly employee: Karen Price <a href="/keyword/social-security-number/" >social security number</a> : 222222222 hourly wage: $16.75; hours worked: 40.00 earned $670.00 commission employee: Sue Jones <a href="/keyword/social-security-number/" >social security number</a> : 333333333 gross sales: $10,000.00; commission rate: 0.06 earned $600.00 basesalaried commission employee: Bob Lewis <a href="/keyword/social-security-number/" >social security number</a> : 444444444 gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00 new base salary with 10% increase is: $330.00 earned $530.00 Employee 0 is a SalariedEmployee Employee 1 is a HourlyEmployee Employee 2 is a CommissionEmployee Employee 3 is a BasePlusCommissionEmployee Outline Same results as when the employees were processed individually 39 PayrollSystemT est .java (5 of 5) Base salary is increased by 10% Each employee's type is displayed 2005 Pearson Education, Inc. All rights reserved. 10.5.6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting Dynamic binding Also known as late binding Calls to overridden methods are resolved at execution time, based on the type of object referenced 40 instanceof operator Determines whether an object is an instance of a certain type 2005 Pearson Education, Inc. All rights reserved. 41 Common Programming Error 10.3 Assigning a superclass variable to a subclass variable (without an explicit cast) is a compilation error. 2005 Pearson Education, Inc. All rights reserved. 42 Software Engineering Observation 10.5 If at execution time the reference of a subclass object has been assigned to a variable of one of its direct or indirect superclasses, it is acceptable to cast the reference stored in that superclass variable back to a reference of the subclass type. Before performing such a cast, use the instanceof operator to ensure that the object is indeed an object of an appropriate subclass type. 2005 Pearson Education, Inc. All rights reserved. 43 Common Programming Error 10.4 When downcasting an object, a ClassCastException occurs, if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its superclasses. 2005 Pearson Education, Inc. All rights reserved. 10.5.6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting (Cont.) Downcasting Convert a reference to a superclass to a reference to a subclass Allowed only if the object has an is-a relationship with the subclass 44 getClass method Inherited from Object Returns an object of type Class getName method of class Class Returns the class's name 2005 Pearson Education, Inc. All rights reserved. 10.5.7 Summary of the Allowed Assignments Between Superclass and Subclass Variables Superclass and subclass assignment rules Assigning a superclass reference to a superclass variable is straightforward Assigning a subclass reference to a subclass variable is straightforward Assigning a subclass reference to a superclass variable is safe because of the is-a relationship Referring to subclass-only members through superclass variables is a compilation error 45 Assigning a superclass reference to a subclass variable is a compilation error Downcasting can get around this error 2005 Pearson Education, Inc. All rights reserved. 46 10.6 final Methods and Classes final methods Cannot be overridden in a subclass private and static methods are implicitly final final methods are resolved at compile time, this is known as static binding Compilers can optimize by inlining the code final classes Cannot be extended by a subclass All methods in a final class are implicitly final 2005 Pearson Education, Inc. All rights reserved. 47 Performance Tip 10.1 The compiler can decide to inline a final method call and will do so for small, simple final methods. Inlining does not violate encapsulation or information hiding, but does improve performance because it eliminates the overhead of making a method call. 2005 Pearson Education, Inc. All rights reserved. 48 Common Programming Error 10.5 Attempting to declare a subclass of a final class is a compilation error. 2005 Pearson Education, Inc. All rights reserved. 49 Software Engineering Observation 10.6 In the Java API, the vast majority of classes are not declared final . This enables inheritance and polymorphism--the fundamental capabilities of object-oriented programming. However, in some cases, it is important to declare classes final --typically for security reasons. 2005 Pearson Education, Inc. All rights reserved. 10.7 Case Study: Creating and Using Interfaces Interfaces Keyword interface Contains only constants and abstract methods All fields are implicitly public, static and final All methods are implicitly public abstract methods 50 Classes can implement interfaces The class must declare each method in the interface using the same signature or the class must be declared abstract Typically used when disparate classes need to share common methods and constants Normally declared in their own files with the same names as the interfaces and with the .java file-name extension 2005 Pearson Education, Inc. All rights reserved. 51 Good Programming Practice 10.1 According to Chapter 9 of the Java Language Specification, it is proper style to declare an interface's methods without keywords public and abstract because they are redundant in interface method declarations. Similarly, constants should be declared without keywords public , static and final because they, too, are redundant. 2005 Pearson Education, Inc. All rights reserved. 52 Common Programming Error 10.6 Failing to implement any method of an interface in a concrete class that im plements the interface results in a syntax error indicating that the class must be declared abstract . 2005 Pearson Education, Inc. All rights reserved. 53 10.7.1 Developing a Payable Hierarchy Payable interface Contains method getPaymentAmount Is implemented by the Invoice and Employee classes UML representation of interfaces Interfaces are distinguished from classes by placing the word "interface" in guillemets ( and ) above the interface name The relationship between a class and an interface is known as realization A class "realizes" the method of an interface 2005 Pearson Education, Inc. All rights reserved. 54 Good Programming Practice 10.2 When declaring a method in an interface, choose a method name that describes the method's purpose in a general manner, because the method may be implemented by a broad range of unrelated classes. 2005 Pearson Education, Inc. All rights reserved. 55 Fig. 10.10 | Payable interface hierarchy UML class diagram. 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 // Fig. 10.11: Payable.java // Payable interface declaration. public interface Payable { double getPaymentAmount(); // calculate payment; no implementation } // end interface Payable Outline Declare interface Payable Payable.java 56 Declare getPaymentAmount method which is implicitly public and abstract 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 // Fig. 10.12: Invoice.java // Invoice class implements Payable. public class Invoice implements Payable { private String partNumber; private String partDescription; private int quantity; private double pricePerItem; Outline Class Invoice implements interface Payable Invoice.java 57 11 // fourargument constructor 12 public Invoice( String part, String description, int count, 13 double price ) 14 { 15 partNumber = part; 16 partDescription = description; 17 setQuantity( count ); // validate and store quantity 18 setPricePerItem( price ); // validate and store price per item 19 } // end fourargument Invoice constructor 20 21 // set part number 22 public void setPartNumber( String part ) 23 { 24 partNumber = part; 25 } // end method setPartNumber 26 (1 of 3) 2005 Pearson Education, Inc. All rights reserved. 27 // get part number 28 public String getPartNumber() 29 { 30 return partNumber; 31 } // end method getPartNumber 32 33 // set description 34 public void setPartDescription( String description ) 35 { 36 partDescription = description; 37 } // end method setPartDescription 38 39 // get description 40 public String getPartDescription() 41 { 42 return partDescription; 43 } // end method getPartDescription 44 45 // set quantity 46 public void setQuantity( int count ) 47 { 48 quantity = ( count < 0 ) ? 0 : count; // quantity cannot be negative 49 } // end method setQuantity 50 51 // get quantity 52 public int getQuantity() 53 { 54 return quantity; 55 } // end method getQuantity 56 Outline Invoice.java 58 (2 of 3) 2005 Pearson Education, Inc. All rights reserved. 57 58 59 60 61 62 63 64 65 66 67 68 69 // set price per item public void setPricePerItem( double price ) { pricePerItem = ( price < 0.0 ) ? 0.0 : price; // validate price } // end method setPricePerItem // get price per item public double getPricePerItem() { return pricePerItem; } // end method getPricePerItem // return String representation of Invoice object Outline Invoice.java 59 (3 of 3) 70 public String toString() 71 { 72 return String.format( "%s: \n%s: %s (%s) \n%s: %d \n%s: $%,.2f", 73 74 75 76 77 78 79 80 81 82 "invoice", "part number", getPartNumber(), getPartDescription(), "quantity", getQuantity(), "price per item", getPricePerItem() ); } // end method toString // method required to carry out contract with interface Payable public double getPaymentAmount() { return getQuantity() * getPricePerItem(); // calculate total cost } // end method getPaymentAmount Declare getPaymentAmount } // end class Invoice to fulfill contract with interface Payable 2005 Pearson Education, Inc. All rights reserved. 60 10.7.3 Creating Class Invoice A class can implement as many interfaces as it needs Use a comma-separated list of interface names after keyword implements Example: public class ClassName extends SuperclassName implements FirstInterface, SecondInterface, ... 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 10.13: Employee.java // Employee abstract superclass implements Payable. public abstract class Employee implements Payable { private String firstName; private String lastName; private String socialSecurityNumber; Outline Em ployee.java 61 Class Employee implements interface Payable 10 // threeargument constructor 11 public Employee( String first, String last, String ssn ) 12 { 13 firstName = first; 14 lastName = last; 15 socialSecurityNumber = ssn; 16 } // end threeargument Employee constructor 17 (1 of 3) 2005 Pearson Education, Inc. All rights reserved. 18 // set first name 19 public void setFirstName( String first ) 20 { 21 firstName = first; 22 } // end method setFirstName 23 24 // return first name 25 public String getFirstName() 26 { 27 return firstName; 28 } // end method getFirstName 29 30 // set last name 31 public void setLastName( String last ) 32 { 33 lastName = last; 34 } // end method setLastName 35 36 // return last name 37 public String getLastName() 38 { 39 return lastName; 40 } // end method getLastName 41 Outline Em ployee.java 62 (2 of 3) 2005 Pearson Education, Inc. All rights reserved. 42 // set <a href="/keyword/social-security-number/" >social security number</a> 43 public void setSocialSecurityNumber( String ssn ) 44 { 45 socialSecurityNumber = ssn; // should validate 46 } // end method setSocialSecurityNumber 47 48 // return <a href="/keyword/social-security-number/" >social security number</a> 49 public String getSocialSecurityNumber() 50 { 51 return socialSecurityNumber; 52 } // end method getSocialSecurityNumber 53 54 // return String representation of Employee object 55 public String toString() 56 { 57 return String.format( "%s %s\n<a href="/keyword/social-security-number/" >social security number</a> : %s", 58 getFirstName(), getLastName(), getSocialSecurityNumber() ); 59 } // end method toString 60 61 // Note: We do not implement Payable method getPaymentAmount here so 62 // this class must be declared abstract to avoid a compilation error. 63 } // end abstract class Employee Outline Em ployee.java 63 (3 of 3) getPaymentAmount method is not implemented here 2005 Pearson Education, Inc. All rights reserved. 10.7.5 Modifying Class SalariedEmployee for Use in the Payable Hierarchy Objects of any subclasses of the class that implements the interface can also be thought of as objects of the interface A reference to a subclass object can be assigned to an interface variable if the superclass implements that interface 64 2005 Pearson Education, Inc. All rights reserved. 65 Software Engineering Observation 10.7 Inheritance and interfaces are similar in their implementation of the "is-a" relationship. An object of a class that implements an interface may be thought of as an object of that interface type. An object of any subclasses of a class that implements an interface also can be thought of as an object of the interface type. 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Fig. 10.14: SalariedEmployee.java // SalariedEmployee class extends Employee, which implements Payable. public class SalariedEmployee extends Employee { private double weeklySalary; // fourargument constructor public SalariedEmployee( String first, String last, String ssn, Outline 66 Class SalariedEmployee extends class Employee (which implements interface Payable) SalariedEm ployee .java 10 double salary ) 11 { 12 super( first, last, ssn ); // pass to Employee constructor 13 setWeeklySalary( salary ); // validate and store salary 14 } // end fourargument SalariedEmployee constructor 15 16 // set salary 17 public void setWeeklySalary( double salary ) 18 { 19 weeklySalary = salary < 0.0 ? 0.0 : salary; 20 } // end method setWeeklySalary 21 (1 of 2) 2005 Pearson Education, Inc. All rights reserved. 22 // return salary 23 public double getWeeklySalary() 24 { 25 return weeklySalary; 26 } // end method getWeeklySalary 27 28 // calculate earnings; implement interface Payable method that was 29 // abstract in superclass Employee 30 public double getPaymentAmount() 32 Outline 67 SalariedEm ployee .java Declare getPaymentAmount 31 { 33 } // end method getPaymentAmount 34 35 // return String representation of SalariedEmployee object 36 public String toString() 37 { 38 return String.format( "salaried employee: %s\n%s: $%,.2f", 39 super.toString(), "weekly salary", getWeeklySalary() ); 40 } // end method toString 41 } // end class SalariedEmployee method return getWeeklySalary(); method instead of earnings (2 of 2) 2005 Pearson Education, Inc. All rights reserved. 68 Software Engineering Observation 10.8 The "is-a" relationship that exists between superclasses and subclasses, and between interfaces and the classes that implement them, holds when passing an object to a method. When a method parameter receives a variable of a superclass or interface type, the method processes the object received as an argument polymorphically. 2005 Pearson Education, Inc. All rights reserved. 69 Software Engineering Observation 10.9 Using a superclass reference, we can polymorphically invoke any method specified in the superclass declaration (and in class Object ). Using an interface reference, we can polymorphically invoke any method specified in the interface declaration (and in class Object ). 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 // Fig. 10.15: PayableInterfaceTest.java // Tests interface Payable. public class PayableInterfaceTest { public static void main( String args[] ) { // create fourelement Payable array Payable payableObjects[] = new Payable[ 4 ]; Outline Declare array of Payable variables 70 PayableInterface T est.java 11 // populate array with objects that implement Payable 12 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 ); 13 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 ); 14 payableObjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", "111111111", 800.00 ); 16 payableObjects[ 3 ] = 17 new SalariedEmployee( "Lisa", "Barnes", "888888888", 1200.00 ); 18 Assigning references to (1 of 2) objects to Invoice Payable variables 19 System.out.println( 20 "Invoices and Employees processed polymorphically:\n" ); Assigning references to 21 SalariedEmployee objects to Payable variables 2005 Pearson Education, Inc. All rights reserved. 22 // generically process each element in array payableObjects 23 for ( Payable currentPayable : payableObjects ) 24 { 25 // output currentPayable and its appropriate payment amount 26 System.out.printf( "%s \n%s: $%,.2f\n\n", 27 currentPayable.toString(), 28 "payment due", currentPayable.getPaymentAmount() ); 29 } // end for 30 } // end main 31 } // end class PayableInterfaceTest Invoices and Employees processed 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 <a href="/keyword/social-security-number/" >social security number</a> : 111111111 weekly salary: $800.00 payment due: $800.00 salaried employee: Lisa Barnes <a href="/keyword/social-security-number/" >social security number</a> : 888888888 weekly salary: $1,200.00 payment due: $1,200.00 Outline 71 PayableInterface T est.java Call toString and getPaymentAmount methods polymorphically (2 of 2) 2005 Pearson Education, Inc. All rights reserved. 72 Software Engineering Observation 10.10 All methods of class Object can be called by using a reference of an interface type. A reference refers to an object, and all objects inherit the methods of class Object . 2005 Pearson Education, Inc. All rights reserved. 10.7.7 Declaring Constants with Interfaces Interfaces can be used to declare constants used in many class declarations These constants are implicitly public, static and final Using a static import declaration allows clients to use these constants with just their names 73 2005 Pearson Education, Inc. All rights reserved. 74 Software Engineering Observation 10.11 As of J2SE 5.0, it is considered a better programming practice to create sets of constants as enumerations with keyword enum . See Section 6.10 for an introduction to enum and Section 8.9 for additional enum details. 2005 Pearson Education, Inc. All rights reserved. 75 Interface Comparable Description As you learned in Chapter 2, Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a class that implements the interface to be compared to one another. The interface contains one method, compareTo, that compares the object that calls the method to the object passed as an argument to the method. Classes must implement compareTo such that it returns a value indicating whether the object on which it is invoked is less than (negative integer return value), equal to (0 return value) or greater than (positive integer return value) the object passed as an argument, using any criteria specified by the programmer. For example, if class Employee implements Comparable, its compareTo method could compare Employee objects by their earnings amounts. Interface Comparable is commonly used for ordering objects in a collection such as an array. We use Comparable in Chapter 18, Generics, and Chapter 19, Collections. Serializable A tagging interface used only to identify classes whose objects can be written to (i.e., serialized) or read from (i.e., deserialized) some type of storage (e.g., file on disk, database field) or transmitted across a network. We use Serializable in Chapter 14, Files and Streams, and Chapter 24, Networking. Fig. 10.16 | Common interfaces of the Java API. (Par t 1 of 2) 2005 Pearson Education, Inc. All rights reserved. 76 Interface Runnable Description Implemented by any class for which objects of that class should be able to execute in parallel using a technique called multithreading (discussed in Chapter 23, Multithreading). The interface contains one method, run, which describes the behavior of an object when executed. GUI event-listener interfaces You work with Graphical User Interfaces (GUIs) every day. For example, in your Web browser, you might type in a text field the address of a Web site to visit, or you might click a button to return to the previous site you visited. When you type a Web site address or click a button in the Web browser, the browser must respond to your interaction and perform the desired task for you. Your interaction is known as an event, and the code that the browser uses to respond to an event is known as an event handler. In Chapter 11, GUI Components: Part 1, and Chapter 22, GUI Components: Part 2, you will learn how to build Java GUIs and how to build event handlers to respond to user interactions. The event handlers are declared in classes that implement an appropriate event-listener interface. Each event listener interface specifies one or more methods that must be implemented to respond to user interactions. SwingConstants Contains a set of constants used in GUI programming to position GUI elements on the screen. We explore GUI programming in Chapters 11 and 22. Fig. 10.16 | Common interfaces of the Java API. (Par t 2 of 2) 2005 Pearson Education, Inc. All rights reserved. 77 Fig. 10.17 | MyShape hierarchy. 2005 Pearson Education, Inc. All rights reserved. 78 Fig. 10.18 | MyShape hierarchy with MyBoundedShape . 2005 Pearson Education, Inc. All rights reserved. 79 Fig. 10.19 | Attributes and operations of classes BalanceInq uir y, Withdrawal and Deposit. 2005 Pearson Education, Inc. All rights reserved. 10.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System UML model for inheritance The generalization relationship The superclass is a generalization of the subclasses The subclasses are specializations of the superclass 80 Transaction superclass Contains the methods and fields BalanceInquiry, Withdrawal and Deposit have in common execute method accountNumber field 2005 Pearson Education, Inc. All rights reserved. 81 Fig. 10. 20 | Class diagram modeling generalization of superclass Transaction and subclasses BalanceInq uir y , Withdrawal and Deposit . Note that abstract class names (e.g., Transaction ) and method names (e.g., execute in class Transaction ) appear in italics. 2005 Pearson Education, Inc. All rights reserved. 82 inheritance). Note that abstract class names (e.g., Transaction) appear in italics. Fig. 10.21 | Class diagram of the ATM system (incorporating 2005 Pearson Education, Inc. All rights reserved. 83 Software Engineering Observation 10.12 A complete class diagram shows all the associations among classes and all the attributes and operations for each class. When the number of class attributes, methods and associations is substantial (as in Fig. 10.21 and Fig. 10.22), a good practice that promotes readability is to divide this information between two class diagrams--one focusing on associations and the other on attributes and methods. 2005 Pearson Education, Inc. All rights reserved. 10.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System (Cont.) Incorporating inheritance into the ATM system design If class A is a generalization of class B, then class B extends class A If class A is an abstract class and class B is a subclass of class A, then class B must implement the abstract methods of class A if class B is to be a concrete class 84 2005 Pearson Education, Inc. All rights reserved. 85 Fig. 10.22 | Class diagram with attributes and operations (incorporating inheritance). Note that abstract class names (e.g., Transaction) and method names (e.g., execute in class Transaction) appear in italic 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 // Class Withdrawal represents an ATM withdrawal transaction public class Withdrawal extends Transaction { } // end class Withdrawal Outline Withdrawal.java 86 Subclass Withdrawal extends superclass Transaction 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Withdrawal.java // Generated using the class diagrams in Fig. 10.21 and Fig. 10.22 public class Withdrawal extends Transaction { // attributes private double amount; // amount to withdraw private Keypad keypad; // reference to keypad private CashDispenser cashDispenser; // reference to cash dispenser Outline Withdrawal.java 87 Subclass Withdrawal extends superclass Transaction 10 // noargument constructor 11 public Withdrawal() 12 { 13 } // end noargument Withdrawal constructor 14 15 // method overriding execute 16 public void execute() 17 { 18 } // end method execute 19 } // end class Withdrawal 2005 Pearson Education, Inc. All rights reserved. 88 Software Engineering Observation 10.13 Several UML modeling tools convert UML-based designs into Java code and can speed the implementation process considerably. For more information on these tools, refer to the Internet and Web Resources listed at the end of Section 2.9. 2005 Pearson Education, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 // Abstract class Transaction represents an ATM transaction public abstract class Transaction { Outline Transaction 89 Declare abstract superclass // attributes private int accountNumber; // indicates account involved private Screen screen; // ATM's screen private BankDatabase bankDatabase; // account info database // noargument constructor invoked by subclasses using super() Transaction.java 10 public Transaction() 11 { 12 } // end noargument Transaction constructor 13 14 // return account number 15 public int getAccountNumber() 16 { 17 } // end method getAccountNumber 18 (1 of 2) 2005 Pearson Education, Inc. All rights reserved. 19 // return reference to screen 20 public Screen getScreen() 21 { 22 } // end method getScreen 23 24 // return reference to bank database 25 public BankDatabase getBankDatabase() 26 { 27 } // end method getBankDatabase 28 29 // abstract method overridden by subclasses 30 public abstract void execute(); 31 } // end class Transaction Outline 90 Transaction.java (2 of 2) Declare abstract method execute 2005 Pearson Education, Inc. All rights reserved.
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more.
Course Hero has millions of course specific materials providing students with the best way to expand
their education.
Below is a small sample set of documents:
LeTourneau - COSC - 2103
18Classes and Objects: A Deeper Look 2005 Pearson Education, Inc. All rights reserved. 2Instead of this absurd division into sexes, they ought to class people as static and dynamic.- Evelyn WaughIs it a world to hide virtues in?- Wi
LeTourneau - COSC - 2103
Chapter 1 Introduction to Computers, the Internet, and the WebOutline 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 Introduction What Is a Computer? Computer Organization Evolution of Operating Systems Personal,
LeTourneau - COSC - 2103
1Chapter 6 - MethodsOutline 6.1 Introduction 6.2 Program Modules in Java 6.3 MathClass Methods 6.4 Method Declarations 6.5 Argument Promotion 6.6 Java API Packages 6.7 RandomNumber Generation 6.8 Example: A Game of Chance 6.9 Sc
LeTourneau - COSC - 2103
Chapter 7 - ArraysOutline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference Parameters 7.6 Passing Arrays to Methods 7.7 Sorting Arrays 7.8 Searching Arrays: Linear S
LeTourneau - COSC - 2103
Chapter 12 - Graphics and Java 2DOutline 12.1 Introduction 12.2 Graphics Contexts and Graphics Objects 12.3 Color Control 12.4 Font Control 12.5 Drawing Lines, Rectangles and Ovals 12.6 Drawing Arcs 12.7 Drawing Polygons and Polylines
LeTourneau - COSC - 2103
Chapter 13 - Graphical User Interface Components: Part 1Outline 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 13.12 13.13 13.14 Introduction Overview of Swing Components JLabel Event Handling TextFields How Eve
LeTourneau - COSC - 2103
Chapter 15 Exception HandlingOutline 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 Introduction ExceptionHandling Overview ExceptionHandling Example: Divide by Zero Java Exception Hierarchy Rethrowing an Exception f
LeTourneau - COSC - 2103
Chapter 16 MultithreadingOutline 16.1 Introduction 16.2 Thread States: Life Cycle of a Thread 16.3 Thread Priorities and Thread Scheduling 16.4 Creating and Executing Threads 16.5 Thread Synchronization 16.6 Producer/Consumer Relationsh
LeTourneau - COSC - 2103
Chapter 17 Files and StreamsOutline 17.1 17.2 17.3 17.4 17.5 17.6 17.7 17.8 17.9 17.10 17.11 17.12 17.13 Introduction Data Hierarchy Files and Streams Class File Creating a SequentialAccess File Reading Data from a Sequent
LeTourneau - COSC - 2103
Chapter 18 - NetworkingOutline 18.1 18.2 18.3 18.4 18.5 18.6 18.7 18.8 18.9 18.10 Introduction Manipulating URLs Reading a File on a Web Server Establishing a Simple Server Using Stream Sockets Establishing a Simple Client Using
LeTourneau - COSC - 2103
Chapter 19 Multimedia: Images, Animation and AudioOutline 19.1 Introduction 19.2 Loading, Displaying and Scaling Images 19.3 Animating a Series of Images 19.4 Image Maps 19.5 Loading and Playing Audio Clips 19.6 Internet and World Wid
LeTourneau - COSC - 2103
Chapter 20 Data StructuresOutline 20.1 20.2 20.3 20.4 20.5 20.6 20.7 Introduction SelfReferential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees 2003 Prentice Hall, Inc. All rights reserved.20.1 Introduction
LeTourneau - COSC - 2103
Chapter 21 Java Utilities Package and Bit ManipulationOutline 21.1 21.2 21.3 21.4 21.5 21.6 21.7 Introduction Vector Class and Enumeration Interface Stack Class of Package java.util Hashtable Class Properties Class Bit Manipulation an
LeTourneau - COSC - 2103
Chapter 22 CollectionsOutline 22.1 22.2 22.3 22.4 22.5 22.6 Introduction Collections Overview Class Arrays Interface Collection and Class Collections Lists Algorithms 22.6.1 Algorithm sort 22.6.2 Algorithm shuffle 22.6.3 Algorithms reverse, fill, c
LeTourneau - COSC - 2103
Chapter 23: Java Database TM Connectivity with JDBCOutline 23.1 23.2 23.3 23.4 Introduction RelationalDatabase Model Relational Database Overview: The books Database SQL 23.4.1 Basic SELECT Query 23.4.2 WHERE Clause 23.4.3 ORDER BY Clause
LeTourneau - COSC - 2103
Chapter 24: ServletsOutline 24.1 Introduction 24.2 Servlet Overview and Architecture 24.2.1 Interface Servlet and the Servlet Life Cycle 24.2.2 HttpServlet Class 24.2.3 HttpServletRequest Interface 24.2.4 HttpServletResponse Interface 24.3
LeTourneau - COSC - 2103
Chapter 25: JavaServer PagesOutline 25.1 25.2 25.3 25.4 25.5 25.6 Introduction JavaServer Pages Overview First JavaServer Page Example Implicit Objects Scripting 25.5.1 Scripting Components 25.5.2 Scripting Example Standard Actions 25.
LeTourneau - COSC - 2103
Appendix D Elevator Events and Listener InterfacesOutlineD.1 D.2 D.3 D.4 Introduction Events Listeners Artifacts Revisited 2001 Prentice Hall, Inc. All rights reserved.D.1 Introduction Event handling Object register as "listeners" for
LeTourneau - COSC - 2103
Appendix F Elevator ViewOutlineF.1 F.2 F.3 F.4 F.5 Introduction Class Objects Class Constants Class Constructor Event Handling F.5.1 ElevatorMoveEvent types F.5.2 PersonMoveEvent types F.5.3 DoorEvent types F.5.4 ButtonEvent types F.5.5 BellEvent
LeTourneau - COSC - 2103
SChicago382002air hammer122SDFW572002airport jets93SMilwaukee3242002automobiles80ASan Francisco4232002breathing difficulties19ANew Orleans11112002coughing30WDebuque11202002fertilizer0.000404636WSt. Louis86
LeTourneau - COSC - 2103
Introduction to JavaA Brief History of OOP and Java Early high level languages _ More recent languages BASIC, Pascal, C, Ada, Smalltalk, C+, Java _ operating system upgrades prompted the development of the C language Powerful language . but
LeTourneau - COSC - 2103
Introduction to JavaA Brief History of OOP and Java Early high level languages FORTRAN, COBOL, LISP More recent languages BASIC, Pascal, C, Ada, Smalltalk, C+, Java UNIX operating system upgrades prompted the development of the C language P
LeTourneau - COSC - 2103
Java AppletsIntroduction to Java Applet Programs Applications are _ programs executed with Java interpreter Applet is a small program can be placed on a _ will be executed by the web _ give web pages "__ content"2Java Applets Built using
LeTourneau - COSC - 2103
Java AppletsIntroduction to Java Applet Programs Applications are stand alone programsexecuted with Java interpreter Applet is a small program can be placed on a web page will be executed by the web browser give web pages "dynamic content
LeTourneau - COSC - 2103
Java BackgroundA Brief History of OOP and Java Early high level languages FORTRAN, COBOL, LISP More recent languages BASIC, Pascal, C, Ada, Smalltalk, C+, Java UNIX operating system upgrades prompted the development of the C language Powerf
LeTourneau - COSC - 2103
Java BackgroundA Brief History of OOP and Java Early high level languagesFORTRAN, COBOL, LISP BASIC, Pascal, C, Ada, Smalltalk, C+, JavaMore recent languagesUNIX operating system upgrades prompted the development of the C language Powe
LeTourneau - COSC - 2103
More About Classes: Instance MethodsObjectives Look at how to build classes as types Study instance methods Place in context of real world object (temperature) Implement attribute (instance) variables Explain importance of encapsulation and in
LeTourneau - COSC - 2103
S tatic Me thodsObje s ctiveLook at how to build static (class) m thods e S tudy useof m thods ecalling, param te re e rs, turning value sC ontrast re re and prim fe nce itiveparam te passing e r C parede proce for m thods to programde om sign
LeTourneau - COSC - 2103
Java Types and Expressions3.2 Primitive and Reference Types Each data value has a type The type must be declared for all variables& constants The compiler needs this information to allocate memory for the variable or constant to verify that t
LeTourneau - COSC - 2103
Java ClassesJava Classes Consider this simplistic classSpecified publicpublic class ProjInfo {ProjInfo() {System.out.println("This program computes factorial of number"); System.out.println("passed via command line at a DOS prompt"); System.out