59
Review – Inheritance • Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a” relationship. class A extends B{ } • Inherit all members except for constructor • superclass (base class or parent class) and subclass (derived class, extended class, or child class) • Overloading and overriding

Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Embed Size (px)

Citation preview

Page 1: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Review

– Inheritance • Inheritance is a relationship between a more general class (the

superclass) and a more specialized class (the subclass). The “is-a” relationship.

class A extends B{

}

• Inherit all members except for constructor

• superclass (base class or parent class) and subclass (derived class, extended class, or child class)

• Overloading and overriding

Page 2: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Interfaces

• Need arising from software engineering– Disparate groups of programmers need to agree to a

“contract” that spells out how their software interacts

– Write your own code without seeing the implementation of other classes (by other programmers)

– An Interface is such a “contract”

• An interface declares a type of object by specifying what the object does– Doesn’t care about the implementation

– Only what functionality is provided

– Specifies common operations

Page 3: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Example

Car manufacturers

Car: start, stop, accelerate, turn right, …

Guidance manufacturers

Invoke the car methods for navigation

There has to be an industry standard as to which methods should be implemented by all car manufacturers

Page 4: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Another motivation

• Multiple inheritance– A class inherits from more than one parents

• A Dog can be both an Animal and a Speaker

• Jack can be both a Person and an Employee

– In C++, a class can inheritance from more than one classes

– In Java, multiple inheritance is done through multiple interfaces

Page 5: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Interfaces

• A collection of constants and abstract methods – without any implementation!

• Different from abstract classes– Abstract class can also have variables and non-abstract methods

(with implementation).

public interface Animal{

int LEGS=4; // constants

public void sleep(); // abstract methods

. . .

}

Note:

• No {} in the method declaration – no implementation

• The word “abstract” is not needed

Page 6: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Use an Interface

• Writing a class the implements an interface– Provides implementation for each method defined in the

interface

• An interface cannot be instantiated

public class Dog implements Animal{

public void sleep(){

System.out.println(“Snorrrr”);

}

}

not extends!

Page 7: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Multiple Inheritance

interface Speaker{

public void speak();

}

interface Animal{

final int LEGS=4;

public void sleep();

}

class Dog implements Speaker, Animal {

public void speak(){

System.out.println("woof");

}

public void sleep(){

System.out.println("snorrrr");

}

public String toString(){

String s="This Dog has " + LEGS + " legs.";

return s;

}

}

Page 8: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

class Teacher implements Speaker{

private String thoughts;

public Teacher (String t) {

thoughts=t;

}

public void speak () {

System.out.println(thoughts);

}

public void repeat() {

for (int i=1; i<=3; i++)

System.out.println(thoughts);

}

}

public class ExInterfaces {

public static void main(String[] args){

Dog little = new Dog();

little.speak();

little.sleep();

System.out.println(

little.toString() );

Teacher tom = new Teacher("Do your homework");

tom.speak();

tom.repeat();

}

}

Page 9: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Converting Between Class and Interface Types

• Very similar to the case of converting between superclass and subclass references– Converting from class to interface reference

Teacher t = new Teacher();

Speaker sp = t; //OK…

method: public void test(Speaker speaker){…} You can call this method by test(t); sp.repeat(); //Error

– Converting from interface reference to class referenceTeacher teacher = (Teacher) sp;teather.repeat();

Page 10: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Some Useful Interfaces

• Comparable– the compareTo() method:

public interface Comparable{ public int compareTo(Object o);

}

– String implements Comparable– Why is it useful? Ex: Arrays.sort(Object[] a)

Page 11: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Introduction to Polymorphism

• Polymorphism– “having many forms”

– Helps build extensible systems

– Programs generically process objects as superclass objects• Can add classes to systems easily

– Classes must be part of generically processed hierarchy

– Can be done through interfaces and abstract classes

Page 12: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Example

public class ExInterfaces {

public static void main(String[] args){

Speaker current;

current = new Dog();

current.speak();

current = new Teacher("Do your homework");

current.speak();

}

}

Different speak() method will be called depending on what type of objects the current reference points to.

The decision as to which one to call cannot be done at compile time. It has to wait until execution time.

Page 13: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Using if-else Statements?

• if-else-based system– Determine appropriate action for object

• Based on object’s type

– Error prone• Programmer can forget to make appropriate type test

• Adding and deleting if-else statements

Page 14: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

class Animal { //...}class Dog extends Animal { public void woof() { System.out.println("Woof!"); } //...}class Cat extends Animal { public void meow() { System.out.println("Meow!"); } //...}class Example5 { public static void main(String[] args) { makeItTalk(new Cat()); makeItTalk(new Dog()); } public static void makeItTalk(Animal animal) { if (animal instanceof Cat) { Cat cat = (Cat) animal; cat.meow(); } else if (animal instanceof Dog) { Dog dog = (Dog) animal; dog.woof(); } }}

Example: using if-else and instanceof

Page 15: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Dynamic Method Binding

• Dynamic method binding– Also called “late binding”

– Implements polymorphic processing of objects

– Use superclass reference to refer to subclass object

– Program chooses “correct” method in subclass at execution

Page 16: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

import java.util.Scanner; public class AnimalGame{      public static void main(String[] args)       {            System.out.println("Choose one of three doors by entering the number of the door you choose.");             Scanner input = new Scanner(System.in);             int doorNumber = input.nextInt();

            Animal animal = null;

            if (doorNumber == 1){                  animal = new Cat();            }           else if (doorNumber == 2){                  animal = new Dog();            }            else {                  System.out.println("Not a valid door number");                  System.exit(1);             }

            System.out.println("The animal behind your door says: " + animal.talk());     }}

Animal is an interface

Dog and Cat implement Animal

Example

Page 17: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Dynamic Method Binding (cont.)

• Example– Superclass Shape– Subclasses Circle, Rectangle and Square– Each class draws itself according to type of class

• Shape has method draw• Each subclass overrides method draw• Call method draw of superclass Shape

– Program determines dynamically which subclass draw method to invoke

Page 18: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Late Binding vs. Early Binding

• Early Binding– Overloaded methods/constructors

– E.g., two constructors for BankAccount class• BankAccount() and BankAccount(double)

• The compiler selects the correct constructor when compiling the program by looking at the parameters.

account = new BankAccount(); //compiler selects BankAccount();

account = new BankAccount(1.00);//BankAccount(double)

• Early Binding – decisions are made at compilation time by the compiler

• Late Binding – decision are made at run time by the java virtual machine

Page 19: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Case Study: A Payroll System Using Polymorphism

• Abstract methods and polymorphism– Abstract superclass Employee

• Method earnings applies to all employees

• Person’s earnings dependent on type of Employee

– Concrete Employee subclasses declared final• Boss• CommissionWorker• PieceWorker• HourlyWorker

Employee

Boss CommissionWorker PieceWorker HourlyWorker

Page 20: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Employee.java

Line 4abstract class cannot be instantiated

Lines 5-6 and 16-30abstract class can have instance data and nonabstract methods for subclasses

Lines 9-13abstract class can have constructors for subclasses to initialize inherited data

1 // Employee.java2 // Abstract base class Employee.3 4 public abstract class Employee {5 private String firstName;6 private String lastName;7 8 // constructor9 public Employee( String first, String last )10 {11 firstName = first;12 lastName = last;13 }14 15 // get first name16 public String getFirstName() 17 { 18 return firstName; 19 }20 21 // get last name22 public String getLastName()23 { 24 return lastName; 25 }26 27 public String toString()28 { 29 return firstName + ' ' + lastName; 30 }31

abstract class cannot be instantiated

abstract class can have instance data and nonabstract methods for subclasses

abstract class can have constructors for subclasses to initialize inherited data

Page 21: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Employee.java

Line 35Subclasses must implement abstract method

32 // Abstract method that must be implemented for each 33 // derived class of Employee from which objects 34 // are instantiated.35 public abstract double earnings(); 36 37 } // end class Employee

Subclasses must implement abstract method

Page 22: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Boss.java

Line 4Boss is an Employee subclass

Line 4Boss inherits Employee’s public methods (except for constuctor)

Line 10Explicit call to Employee constructor using super

Lines 21-24Required to implement Employee’s method earnings (polymorphism)

1 // Boss.java2 // Boss class derived from Employee.3 4 public final class Boss extends Employee {5 private double weeklySalary; 6 7 // constructor for class Boss8 public Boss( String first, String last, double salary )9 {10 super( first, last ); // call superclass constructor11 setWeeklySalary( salary );12 }13 14 // set Boss's salary15 public void setWeeklySalary( double salary )16 { 17 weeklySalary = ( salary > 0 ? salary : 0 ); 18 }19 20 // get Boss's pay21 public double earnings() 22 { 23 return weeklySalary; 24 }25 26 // get String representation of Boss's name27 public String toString() 28 {29 return "Boss: " + super.toString();30 }31 32 } // end class Boss

Boss is an Employee subclass

Boss inherits Employee’s public methods (except for constuctor)

Explicit call to Employee constructor using super

Required to implement Employee’s method earnings (polymorphism)

Page 23: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

CommissionWorker.java

Line 4CommissionWorker is an Employee subclass

Line 13Explicit call to Employee constructor using super

1 // CommissionWorker.java2 // CommissionWorker class derived from Employee3 4 public final class CommissionWorker extends Employee {5 private double salary; // base salary per week6 private double commission; // amount per item sold7 private int quantity; // total items sold for week8 9 // constructor for class CommissionWorker10 public CommissionWorker( String first, String last,11 double salary, double commission, int quantity )12 {13 super( first, last ); // call superclass constructor14 setSalary( salary );15 setCommission( commission );16 setQuantity( quantity );17 }18 19 // set CommissionWorker's weekly base salary20 public void setSalary( double weeklySalary )21 { 22 salary = ( weeklySalary > 0 ? weeklySalary : 0 ); 23 }24 25 // set CommissionWorker's commission26 public void setCommission( double itemCommission ) 27 { 28 commission = ( itemCommission > 0 ? itemCommission : 0 );29 }30

CommissionWorker is an Employee subclass

Explicit call to Employee constructor using super

Page 24: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

CommissionWorker.java

Lines 38-41Required to implement Employee’s method earnings; this implementation differs from that in Boss

31 // set CommissionWorker's quantity sold32 public void setQuantity( int totalSold )33 { 34 quantity = ( totalSold > 0 ? totalSold : 0 ); 35 }36 37 // determine CommissionWorker's earnings38 public double earnings()39 {40 return salary + commission * quantity; 41 }42 43 // get String representation of CommissionWorker's name 44 public String toString() 45 {46 return "Commission worker: " + super.toString();47 }48 49 } // end class CommissionWorker

Required to implement Employee’s method earnings; this implementation

differs from that in Boss

Page 25: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

PieceWorker.java

Line 4PieceWorker is an Employee subclass

Line 12Explicit call to Employee constructor using super

Lines 30-33 Implementation of Employee’s method earnings; differs from that of Boss and CommissionWorker

1 // PieceWorker.java2 // PieceWorker class derived from Employee3 4 public final class PieceWorker extends Employee {5 private double wagePerPiece; // wage per piece output6 private int quantity; // output for week7 8 // constructor for class PieceWorker9 public PieceWorker( String first, String last,10 double wage, int numberOfItems )11 {12 super( first, last ); // call superclass constructor13 setWage( wage );14 setQuantity( numberOfItems);15 }16 17 // set PieceWorker's wage18 public void setWage( double wage ) 19 { 20 wagePerPiece = ( wage > 0 ? wage : 0 ); 21 }22 23 // set number of items output24 public void setQuantity( int numberOfItems ) 25 { 26 quantity = ( numberOfItems > 0 ? numberOfItems : 0 ); 27 }28 29 // determine PieceWorker's earnings30 public double earnings()31 { 32 return quantity * wagePerPiece; 33 }34

PieceWorker is an Employee subclass

Explicit call to Employee constructor using super

Implementation of Employee’s method earnings; differs from that of Boss

and CommissionWorker

Page 26: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

PieceWorker.java

35 public String toString()36 {37 return "Piece worker: " + super.toString();38 } 39 40 } // end class PieceWorker

Page 27: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

HourlyWorker.java

Line 4PieceWorker is an Employee subclass

Line 12Explicit call to Employee constructor using super

Line 31Implementation of Employee’s method earnings; differs from that of other Employee subclasses

1 // HourlyWorker.java2 // Definition of class HourlyWorker3 4 public final class HourlyWorker extends Employee {5 private double wage; // wage per hour6 private double hours; // hours worked for week7 8 // constructor for class HourlyWorker9 public HourlyWorker( String first, String last, 10 double wagePerHour, double hoursWorked )11 {12 super( first, last ); // call superclass constructor13 setWage( wagePerHour );14 setHours( hoursWorked );15 }16 17 // Set the wage18 public void setWage( double wagePerHour )19 { 20 wage = ( wagePerHour > 0 ? wagePerHour : 0 ); 21 }22 23 // Set the hours worked24 public void setHours( double hoursWorked )25 { 26 hours = ( hoursWorked >= 0 && hoursWorked < 168 ?27 hoursWorked : 0 ); 28 }29 30 // Get the HourlyWorker's pay31 public double earnings() { return wage * hours; }32

HourlyWorker is an Employee subclass

Explicit call to Employee constructor using super

Implementation of Employee’s method earnings; differs from that of other

Employee subclasses

Page 28: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

HourlyWorker.java

33 public String toString() 34 {35 return "Hourly worker: " + super.toString();36 }37 38 } // end class HourlyWorker

Page 29: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Test.java

Line 15Test cannot instantiate Employee but can reference one

Lines 18-28Instantiate one instance each of Employee subclasses

1 // Test.java2 // Driver for Employee hierarchy3 4 // Java core packages5 import java.text.DecimalFormat;6 7 // Java extension packages8 import javax.swing.JOptionPane;9 10 public class Test {11 12 // test Employee hierarchy13 public static void main( String args[] )14 {15 Employee employee; // superclass reference16 String output = "";17 18 Boss boss = new Boss( "John", "Smith", 800.0 );19 20 CommissionWorker commisionWorker =21 new CommissionWorker( 22 "Sue", "Jones", 400.0, 3.0, 150 );23 24 PieceWorker pieceWorker =25 new PieceWorker( "Bob", "Lewis", 2.5, 200 );26 27 HourlyWorker hourlyWorker =28 new HourlyWorker( "Karen", "Price", 12.5, 40 );29 30 DecimalFormat precision2 = new DecimalFormat( "0.00" );31

Instantiate one instance each of Employee subclasses

Test cannot instantiate Employee but can reference one

Page 30: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Test.java

Line 33Use Employee to reference Boss

Line 36Method employee.earnings dynamically binds to method boss.earnings

Lines 41-55Do same for CommissionWorker and PieceWorker

32 // Employee reference to a Boss 33 employee = boss; 34 35 output += employee.toString() + " earned $" +36 precision2.format( employee.earnings() ) + "\n" +37 boss.toString() + " earned $" +38 precision2.format( boss.earnings() ) + "\n";39 40 // Employee reference to a CommissionWorker41 employee = commissionWorker;42 43 output += employee.toString() + " earned $" +44 precision2.format( employee.earnings() ) + "\n" +45 commissionWorker.toString() + " earned $" +46 precision2.format( 47 commissionWorker.earnings() ) + "\n";48 49 // Employee reference to a PieceWorker50 employee = pieceWorker;51 52 output += employee.toString() + " earned $" +53 precision2.format( employee.earnings() ) + "\n" +54 pieceWorker.toString() + " earned $" +55 precision2.format( pieceWorker.earnings() ) + "\n";56

Use Employee to reference Boss

Method employee.earnings dynamically binds to method

boss.earnings

Do same for CommissionWorker and PieceWorker

Page 31: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Test.java

Lines 58-63Repeat for HourlyWorker

Line 59Casting is required for accessing subclass methods

57 // Employee reference to an HourlyWorker58 employee = hourlyWorker; 59 ((HourlyWorker)employee).setWage(13.75);60 output += employee.toString() + " earned $" +61 precision2.format( employee.earnings() ) + "\n" +62 hourlyWorker.toString() + " earned $" +63 precision2.format( hourlyWorker.earnings() ) + "\n";64 65 JOptionPane.showMessageDialog( null, output,66 "Demonstrating Polymorphism",67 JOptionPane.INFORMATION_MESSAGE );68 69 System.exit( 0 );70 }71 72 } // end class Test

Repeat for HourlyWorker

Casting required for accessing subclass methods

Page 32: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

New Classes and Dynamic Binding

• Dynamic binding (late binding)– Object’s type need not be known at compile time

– At run time, call is matched with method of called object

– Easy to add new classes to the class hierarchy

Page 33: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Recap - Interfaces

• Interfaces– A collection of constants and abstract methods– No implementation details defined

public interface Car{ final int WHEELS = 4; public void start(); public void stop(); . . .}

– Variables are implicitly defined as public static final• Implementing interfaces

public class Ford implements Car { public void start(){ . . . } public void stop(){ . . . } . . .}

Page 34: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Interfaces

• True or false?– An interface can have private instance attributes

– A concrete class implementing an interface can implement selected methods defined in the interface

– A class can implement more than one interface

– One need to use abstract to indicate that a method is abstract in an interface

– You can create an instance (object) of an interface, just like creating an instance of a class

Page 35: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

interface Silly { public void narf(); public void poit(Silly s);}public class Bird implements Silly { public static void main(String

args[]) { System.out.println("zero"); Silly s = new SillyBird(1); Silly s2 = new Loony(); s.poit(s2); s2.poit(s); System.out.println("zymurgy"); } public Bird() { this(0); System.out.println("zircon"); } public Bird(int i) { System.out.println("zanzibar"); } public void narf() { System.out.println("zort"); } public void poit(Silly s) { s.narf(); }}

class SillyBird extends Bird {

public SillyBird(){ System.out.println("duchess"); }

public SillyBird(int i) { super(i); }

public void narf() { System.out.println("drum"); super.narf(); }}

class Loony extends SillyBird { public Loony() {

System.out.println("stupendous"); } public void narf() { System.out.println("snark"); }}

What’s the output?

Page 36: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

JCheckBox and JRadioButton

• State buttons– On/Off or true/false values

– Java provides three types• JToggleButton• JCheckBox• JRadioButton

Page 37: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 // CheckBoxTest.java 2 // Creating Checkbox buttons. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*;10 11 public class CheckBoxTest extends JFrame {12 private JTextField field;13 private JCheckBox bold, italic;14 15 // set up GUI16 public CheckBoxTest()17 {18 super( "JCheckBox Test" );19 20 // get content pane and set its layout21 Container container = getContentPane();22 container.setLayout( new FlowLayout() );23 24 // set up JTextField and set its font25 field = 26 new JTextField( "Watch the font style change", 20 );27 field.setFont( new Font( "Serif", Font.PLAIN, 14 ) );28 container.add( field );29 30 // create checkbox objects31 bold = new JCheckBox( "Bold" );32 container.add( bold ); 33 34 italic = new JCheckBox( "Italic" );35 container.add( italic );

CheckBoxTest.java

Line 13

Line 27

Lines 31-35Declare two JCheckBox instances

Set JTextField font to Serif, 14-point plain

Instantiate JCheckBoxs for bolding and italicizing JTextField text, respectively

Page 38: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 37 // register listeners for JCheckBoxes38 CheckBoxHandler handler = new CheckBoxHandler();39 bold.addItemListener( handler );40 italic.addItemListener( handler );41 42 setSize( 275, 100 );43 setVisible( true );44 }45 46 // execute application47 public static void main( String args[] )48 { 49 CheckBoxTest application = new CheckBoxTest();50 51 application.setDefaultCloseOperation(52 JFrame.EXIT_ON_CLOSE );53 }54 55 // private inner class for ItemListener event handling56 private class CheckBoxHandler implements ItemListener {57 private int valBold = Font.PLAIN;58 private int valItalic = Font.PLAIN;59 60 // respond to checkbox events61 public void itemStateChanged( ItemEvent event )62 {63 // process bold checkbox events64 if ( event.getSource() == bold )65 66 if ( event.getStateChange() == ItemEvent.SELECTED )67 valBold = Font.BOLD;68 else69 valBold = Font.PLAIN;70

CheckBoxTest.java

Lines 38-40

Line 61

Register JCheckBoxs to receive events from CheckBoxHandler

When user selects JCheckBox, CheckBoxHandler invokes

method itemStateChanges of all registered listeners

Page 39: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

71 // process italic checkbox events72 if ( event.getSource() == italic )73 74 if ( event.getStateChange() == ItemEvent.SELECTED )75 valItalic = Font.ITALIC;76 else77 valItalic = Font.PLAIN;78 79 // set text field font80 field.setFont(81 new Font( "Serif", valBold + valItalic, 14 ) );82 }83 84 } // end private inner class CheckBoxHandler85 86 } // end class CheckBoxTest

CheckBoxTest.java

Lines 80-81Change JTextField font, depending on which JCheckBox was selected

Page 40: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 // RadioButtonTest.java 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*;10 11 public class RadioButtonTest extends JFrame {12 private JTextField field;13 private Font plainFont, boldFont, italicFont, boldItalicFont;14 private JRadioButton plainButton, boldButton, italicButton,15 boldItalicButton;16 private ButtonGroup radioGroup;17 18 // create GUI and fonts19 public RadioButtonTest()20 {21 super( "RadioButton Test" );22 23 // get content pane and set its layout24 Container container = getContentPane();25 container.setLayout( new FlowLayout() );26 27 // set up JTextField28 field = 29 new JTextField( "Watch the font style change", 25 );30 container.add( field ); 31 32 // create radio buttons33 plainButton = new JRadioButton( "Plain", true );34 container.add( plainButton );35

RadioButtonTest.java

Lines 14-15

Line 16

JRadioButtons normally appear as a ButtonGroup

Declare four JRadioButton instances

Page 41: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 boldButton = new JRadioButton( "Bold", false);37 container.add( boldButton );38 39 italicButton = new JRadioButton( "Italic", false );40 container.add( italicButton );41 42 boldItalicButton = new JRadioButton( 43 "Bold/Italic", false );44 container.add( boldItalicButton );45 46 // register events for JRadioButtons47 RadioButtonHandler handler = new RadioButtonHandler();48 plainButton.addItemListener( handler );49 boldButton.addItemListener( handler );50 italicButton.addItemListener( handler );51 boldItalicButton.addItemListener( handler );52 53 // create logical relationship between JRadioButtons54 radioGroup = new ButtonGroup();55 radioGroup.add( plainButton );56 radioGroup.add( boldButton );57 radioGroup.add( italicButton );58 radioGroup.add( boldItalicButton );59 60 // create font objects61 plainFont = new Font( "Serif", Font.PLAIN, 14 );62 boldFont = new Font( "Serif", Font.BOLD, 14 );63 italicFont = new Font( "Serif", Font.ITALIC, 14 );64 boldItalicFont =65 new Font( "Serif", Font.BOLD + Font.ITALIC, 14 );66 field.setFont( plainFont );67 68 setSize( 300, 100 );69 setVisible( true );70 }

RadioButtonTest.java

Lines 36-44

Lines 47-51

Lines 54-58

Instantiate JRadioButtons for manipulating JTextField text font

Register JRadioButtons to receive events from

RadioButtonHandler

JRadioButtons belong to ButtonGroup

Page 42: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

71 72 // execute application73 public static void main( String args[] )74 {75 RadioButtonTest application = new RadioButtonTest();76 77 application.setDefaultCloseOperation(78 JFrame.EXIT_ON_CLOSE );79 }80 81 // private inner class to handle radio button events82 private class RadioButtonHandler implements ItemListener {83 84 // handle radio button events85 public void itemStateChanged( ItemEvent event )86 {87 // user clicked plainButton88 if ( event.getSource() == plainButton ) 89 field.setFont( plainFont );90 91 // user clicked boldButton92 else if ( event.getSource() == boldButton ) 93 field.setFont( boldFont );94 95 // user clicked italicButton96 else if ( event.getSource() == italicButton ) 97 field.setFont( italicFont );98 99 // user clicked boldItalicButton100 else if ( event.getSource() == boldItalicButton ) 101 field.setFont( boldItalicFont );102 }103 104 } // end private inner class RadioButtonHandler105 106 } // end class RadioButtonTest

RadioButtonTest.java

Lines 85-104

Lines 88-102

When user selects JRadioButton, RadioButtonHandler invokes

method itemStateChanged of all registered listeners

Set font corresponding to JRadioButton selected

Page 43: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

RadioButtonTest.java

Page 44: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

JComboBox

• JComboBox– List of items from which user can select

– Also called a drop-down list

Page 45: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 // ComboBoxTest.java 2 // Using a JComboBox to select an image to display. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*;10 11 public class ComboBoxTest extends JFrame {12 private JComboBox imagesComboBox;13 private JLabel label;14 15 private String names[] =16 { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" };17 private Icon icons[] = { new ImageIcon( names[ 0 ] ),18 new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ),19 new ImageIcon( names[ 3 ] ) };20 21 // set up GUI22 public ComboBoxTest()23 {24 super( "Testing JComboBox" );25 26 // get content pane and set its layout27 Container container = getContentPane();28 container.setLayout( new FlowLayout() ); 29 30 // set up JComboBox and register its event handler31 imagesComboBox = new JComboBox( names );32 imagesComboBox.setMaximumRowCount( 3 );33 34 imagesComboBox.addItemListener(35

ComboBoxTest.java

Lines 31-32

Line 34

Register JComboBox to receive events from anonymous ItemListener

Instantiate JComboBox to show three Strings from names array at a time

Page 46: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 // anonymous inner class to handle JComboBox events37 new ItemListener() {38 39 // handle JComboBox event40 public void itemStateChanged( ItemEvent event )41 {42 // determine whether check box selected43 if ( event.getStateChange() == ItemEvent.SELECTED )44 label.setIcon( icons[ 45 imagesComboBox.getSelectedIndex() ] );46 }47 48 } // end anonymous inner class49 50 ); // end call to addItemListener51 52 container.add( imagesComboBox );53 54 // set up JLabel to display ImageIcons55 label = new JLabel( icons[ 0 ] );56 container.add( label );57 58 setSize( 350, 100 );59 setVisible( true );60 }61 62 // execute application63 public static void main( String args[] )64 { 65 ComboBoxTest application = new ComboBoxTest();66 67 application.setDefaultCloseOperation(68 JFrame.EXIT_ON_CLOSE );69 }70 71 } // end class ComboBoxTest

ComboBoxTest.java

Lines 40-46

Lines 43-45When user selects item in JComboBox, ItemListener invokes method

itemStateChanged of all registered listeners

Set appropriate Icon depending on user selection

Page 47: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

ComboBoxTest.java

Page 48: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

JList

• List– Series of items

– user can select one or more items

– Single-selection vs. multiple-selection– JList

Page 49: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 // ListTest.java 2 // Selecting colors from a JList. 3 4 // Java core packages 5 import java.awt.*; 6 7 // Java extension packages 8 import javax.swing.*; 9 import javax.swing.event.*;10 11 public class ListTest extends JFrame {12 private JList colorList;13 private Container container;14 15 private String colorNames[] = { "Black", "Blue", "Cyan", 16 "Dark Gray", "Gray", "Green", "Light Gray", "Magenta",17 "Orange", "Pink", "Red", "White", "Yellow" };18 19 private Color colors[] = { Color.black, Color.blue, 20 Color.cyan, Color.darkGray, Color.gray, Color.green,21 Color.lightGray, Color.magenta, Color.orange, Color.pink,22 Color.red, Color.white, Color.yellow };23 24 // set up GUI25 public ListTest()26 {27 super( "List Test" );28 29 // get content pane and set its layout30 container = getContentPane();31 container.setLayout( new FlowLayout() );32 33 // create a list with items in colorNames array34 colorList = new JList( colorNames );35 colorList.setVisibleRowCount( 5 );

ListTest.java

Line 34

Use colorNames array to populate JList

Page 50: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 37 // do not allow multiple selections38 colorList.setSelectionMode(39 ListSelectionModel.SINGLE_SELECTION );40 41 // add a JScrollPane containing JList to content pane42 container.add( new JScrollPane( colorList ) );43 44 // set up event handler45 colorList.addListSelectionListener(46 47 // anonymous inner class for list selection events48 new ListSelectionListener() {49 50 // handle list selection events51 public void valueChanged( ListSelectionEvent event )52 {53 container.setBackground(54 colors[ colorList.getSelectedIndex() ] );55 }56 57 } // end anonymous inner class58 59 ); // end call to addListSelectionListener60 61 setSize( 350, 150 );62 setVisible( true );63 }64 65 // execute application66 public static void main( String args[] )67 { 68 ListTest application = new ListTest();69

ListTest.java

Lines 38-39

Lines 45-59

Lines 51-55

Lines 53-54

JList allows single selections

Register JList to receive events from anonymous ListSelectionListener

When user selects item in JList, ListSelectionListener

invokes method valueChanged of all registered listeners

Set appropriate background depending on user selection

Page 51: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

70 application.setDefaultCloseOperation(71 JFrame.EXIT_ON_CLOSE );72 }73 74 } // end class ListTest ListTest.java

Page 52: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

Multiple-Selection Lists

• Multiple-selection list– Select many items from Jlist– Allows continuous range selection

Page 53: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 // MultipleSelection.java 2 // Copying items from one List to another. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*;10 11 public class MultipleSelection extends JFrame {12 private JList colorList, copyList;13 private JButton copyButton;14 15 private String colorNames[] = { "Black", "Blue", "Cyan", 16 "Dark Gray", "Gray", "Green", "Light Gray", 17 "Magenta", "Orange", "Pink", "Red", "White", "Yellow" };18 19 // set up GUI20 public MultipleSelection()21 {22 super( "Multiple Selection Lists" );23 24 // get content pane and set its layout25 Container container = getContentPane();26 container.setLayout( new FlowLayout() );27 28 // set up JList colorList29 colorList = new JList( colorNames );30 colorList.setVisibleRowCount( 5 );31 colorList.setFixedCellHeight( 15 );32 colorList.setSelectionMode(33 ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );34 container.add( new JScrollPane( colorList ) );35

MultipleSelection.java

Line 29

Lines 32-33

Use colorNames array to populate JList

JList colorList allows multiple selections

Page 54: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 // create copy button and register its listener37 copyButton = new JButton( "Copy >>>" );38 39 copyButton.addActionListener(40 41 // anonymous inner class for button event42 new ActionListener() {43 44 // handle button event45 public void actionPerformed( ActionEvent event )46 {47 // place selected values in copyList48 copyList.setListData(49 colorList.getSelectedValues() );50 }51 52 } // end anonymous inner class53 54 ); // end call to addActionListener55 56 container.add( copyButton );57 58 // set up JList copyList59 copyList = new JList();60 copyList.setVisibleRowCount( 5 );61 copyList.setFixedCellWidth( 100 );62 copyList.setFixedCellHeight( 15 );63 copyList.setSelectionMode(64 ListSelectionModel.SINGLE_INTERVAL_SELECTION );65 container.add( new JScrollPane( copyList ) );66 67 setSize( 300, 120 );68 setVisible( true );69 }70

MultipleSelection.java

Lines 48-49

Lines 63-64

When user presses JButton, JList copyList adds items that user

selected from JList colorList

JList colorList allows single selections

Page 55: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

71 // execute application72 public static void main( String args[] )73 { 74 MultipleSelection application = new MultipleSelection();75 76 application.setDefaultCloseOperation(77 JFrame.EXIT_ON_CLOSE );78 }79 80 } // end class MultipleSelection

MultipleSelection.java

Page 56: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

JTextArea

• JTextArea vs. JTextField– Multiple lines vs. single line

Page 57: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

1 //========================================================== 2 // TextAreaDemo.java 3 // Copying selected text from one text area to another. 4 import java.awt.*; 5 import java.awt.event.*; 6 import javax.swing.*; 7 8 public class TextAreaDemo extends JFrame { 9 private JTextArea t1, t2; 10 private JButton copy; 11 public TextAreaDemo() { 12 super( "TextArea Demo" ); 13 Box b = Box.createHorizontalBox(); 14 String s = "This is a demo string to\n" + 15 "illustrate copying text\n" + "from one TextArea to \n" + 16 "another TextArea using an\n" + 17 "external event\n"; 18 t1 = new JTextArea( s, 10, 15 ); 19 b.add( new JScrollPane( t1 ) ); 20 copy = new JButton( "Copy >>>" ); 21 copy.addActionListener( 22 new ActionListener() { 23 public void actionPerformed( ActionEvent e ){ 24 t2.setText( t1.getSelectedText() ); 25 } 26 } 27 ); 28 b.add( copy ); 29 t2 = new JTextArea( 10, 15 ); 30 t2.setEditable( false ); 31 b.add( new JScrollPane( t2 ) ); 32 Container c = getContentPane(); 33 c.add( b ); // Box placed in BorderLayout.CENTER 34 setSize( 425, 200 ); 35 show(); 36 }

TextAreaDemo.java

Page 58: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

36 public static void main( String args[] ) { 37 TextAreaDemo app = new TextAreaDemo(); 38 app.addWindowListener( new WindowAdapter() { 39 public void windowClosing( WindowEvent e ) { 40 System.exit( 0 ); 41 } 42 } 43 ); 44 } 44}

TextAreaDemo.java

Page 59: Review –Inheritance Inheritance is a relationship between a more general class (the superclass) and a more specialized class (the subclass). The “is-a”

• Readings– Ch 10

• Assignment 1 is available– Due: June 18th

– Submit: Moodle