Review Why a Null Pointer Exception class Floor

  • Slides: 82
Download presentation
Review

Review

Why a Null. Pointer. Exception? class Floor. View implements Observer { private Elevator elevator;

Why a Null. Pointer. Exception? class Floor. View implements Observer { private Elevator elevator; // the subject private JLabel label; public Floor. View(Elevator elev) { Elevator elevator = elev; JLabel label = new JLabel( "Floor "+elev. get. Floor() ); . . . } public void update(Observable obj, Object arg) { int floor = elevator. get. Floor( ); Null. Pointer. Exception label. set. Text( "Floor "+floor ); Null. Pointer. Exception }

What is a URL? URL = Uniform Resource Locator http: //www. google. com ftp:

What is a URL? URL = Uniform Resource Locator http: //www. google. com ftp: //se. cpe. ku. ac. th/download/readme. html file: ///C: /temp/somefile. txt Even more complex URLs are possible: jdbc: mysql: //se. cpe. ku. ac. th: 3306/world

How do you read a URL? Java has a URL class. You can create

How do you read a URL? Java has a URL class. You can create an Input. Stream to read or write to/from a URL url = new URL( "http: //www. google. com/" ); Input. Stream instream = url. open. Stream( ); // process input data as you like Scanner scanner = new Scanner( instream ); while ( scanner. has. Next. Line() ) {. . . }

How do you create a Color? What do these numbers mean? Color purple =

How do you create a Color? What do these numbers mean? Color purple = new Color(212, 0, 228); What do these numbers mean? red = Color. get. HSBColor(0. 0, 1. 0, 0. 5);

Color Space You can specify any color using 3 numbers. RGB - color given

Color Space You can specify any color using 3 numbers. RGB - color given by level of red, green, and blue. Usually 8 -bits (0 -255) per color. Some digital cameras use 12 -bits per color. CMY - cyan, magenta, yellow HSB - Hue, Saturation, Brightness (Java: float 0. 0 -1. 0) HSL - Hue, Saturation, Luminescence

Calculate the Picture Size A digital camera has resolution 4 Megapixels and 8 -bit

Calculate the Picture Size A digital camera has resolution 4 Megapixels and 8 -bit color depth. 1. How much space to store a photo in TIFF format (no compression)? 2. How much space to store a photo in JPEG format with 10 -to-1 compression?

What is a JAR file? 1. What is the format of a JAR file?

What is a JAR file? 1. What is the format of a JAR file? 2. How do you create a JAR file? Java reads information from a JAR file, such as the name of the "main" class, whether this JAR is a Java. Bean. 3. What file contains this info?

Getting a Reference The Button. Panel for the elevator needs to send messages to

Getting a Reference The Button. Panel for the elevator needs to send messages to the elevator. q How can we give Button. Panel a reference to the Elevator? q

Solution: inject a Reference This is dependency injection. class Button. Panel extends JFrame {

Solution: inject a Reference This is dependency injection. class Button. Panel extends JFrame { private Elevator elevator; public Button. Panel(Elevator lift) { this. elevator = lift; // dependency. . . }

Dependency Injection by setter method Use a "set" method for dependency injection. class Button.

Dependency Injection by setter method Use a "set" method for dependency injection. class Button. Panel extends JFrame { private Elevator elevator; public Button. Panel( ) {. . . } public void set. Elevator(Elevator lift) { this. elevator = lift; // dependency. . . }

Wrong Solution Create the Elevator in the View. class Button. Panel extends JFrame {

Wrong Solution Create the Elevator in the View. class Button. Panel extends JFrame { private Elevator elevator; public Button. Panel( ) { elevator = new Elevator( ); . . . } // wrong

Draw a Sequence Diagram of Dependency Injection. class Main { public void init( )

Draw a Sequence Diagram of Dependency Injection. class Main { public void init( ) { Elevator elevator = new Elevator( ); Button. Panel bp = new Button. Panel( ); bp. set. Elevator( elevator ); elevator. add. Observer( bp ); }

Start Chart Diagram Floor 2 UP DOWN Floor 1 entry/open. Door exit/close. Door

Start Chart Diagram Floor 2 UP DOWN Floor 1 entry/open. Door exit/close. Door

3 Fundamental O-O Characteristics 1. Encapsulation 2. Polymorphism 3. Inheritance

3 Fundamental O-O Characteristics 1. Encapsulation 2. Polymorphism 3. Inheritance

" e p What is Polymorphism? q Define polymorphism. o D " q t

" e p What is Polymorphism? q Define polymorphism. o D " q t ' n k s A t a h Ty W Give the simplest example of polymorphism you can think of (no elevators or observers). Object o = new Coin( 5 ); System. out. println( o. to. String() ); o = new Date( ); System. out. println( o. to. String() );

2 ways to enable Polymorphism? q Name 2 constructs (ways of programming in Java)

2 ways to enable Polymorphism? q Name 2 constructs (ways of programming in Java) we can use to achieve polymorphism? 1. inheritance 2. interface q List coins = new My. List(); Give example of each one. 1. Coin is a subclass of Money q How can we enable polymorphism in our apps?

Notifying Observers The Floor. View must update the display whenever the elevator changes state.

Notifying Observers The Floor. View must update the display whenever the elevator changes state. How is this done? 1. ________ invokes ________ 2. ________ invokes ________ 3. ______ (Observer) calls ________ 4. ________ calls ________

Notifying Observers The Floor. View must update the display whenever the elevator changes state.

Notifying Observers The Floor. View must update the display whenever the elevator changes state. How is this done? 1. Elevator invokes notify. Observers_ 2. notify. Observers() invokes observer. update( ) 3. Floor. View (Observer) calls elevator. get. Floor() 4. Floor. View calls label. set. Text( "Floor "+floor )

Notifying Observers The Floor. View must update when the Elevator moves. How is this

Notifying Observers The Floor. View must update when the Elevator moves. How is this done? Draw and number the method calls.

O-O Fundamentals How are the fundamental O-O characteristics used in the Observer pattern? How

O-O Fundamentals How are the fundamental O-O characteristics used in the Observer pattern? How does this benefit the program?

Views and Controls Views are Observers. They get notified by Subject. Q: Do views

Views and Controls Views are Observers. They get notified by Subject. Q: Do views need a reference to Subject? View 2. wake up! (Observer) 3. what happened? 4. update display Floor 5 Abstract Subject 1. notify observers Subject

Views and Controls send messages to the Subject. Q: Do controls need a reference

Views and Controls send messages to the Subject. Q: Do controls need a reference to the Subject? UP BUTTON Abstract Subject 1. event occurs Control 2. handle this 4. notify observers Subject 3. do something

Elevator Views and Controls q Some components are both observer and control. Notification Path

Elevator Views and Controls q Some components are both observer and control. Notification Path Control Path

Remote Control problem We have a 4 -button Remote Control. Design a solution to

Remote Control problem We have a 4 -button Remote Control. Design a solution to program the Remote Control. Goals: 1. Don't couple Remote Control to a Light. Bulb or any other device. 2. Can program Remote. Control to control anything. 1 2 3 4

Remote Control solution We have a 4 -button Remote Control. Design a solution to

Remote Control solution We have a 4 -button Remote Control. Design a solution to program the Remote Control. 1 2 3 4 click

Use Commands for Remote. Control

Use Commands for Remote. Control

How to Program using an Action class On. Action extends Abstract. Action { private

How to Program using an Action class On. Action extends Abstract. Action { private Light. Bulb light; public On. Action(Light. Bulb light) { super("Light On"); this. light = light; } public void action. Performed( ) { light. turn. On( ); } }

How to Program using an Action (2) Now you can put the action in

How to Program using an Action (2) Now you can put the action in as many components as you want. Action on = new On. Action( ); JButton on. Button = new JButton( on ); Menu. Item mitem = new Menu. Item( on ); menu. add. Item( mitem ); Components will get their name, status, icon from the action. They use On. Action as Action. Listener.

How to Program using an Action (3) You can disable the components by disabling

How to Program using an Action (3) You can disable the components by disabling the action. set. Enabled( false ); Disable all components using this action.

3 O-O Characteristics q q How does the Command Pattern (using Actions) use the

3 O-O Characteristics q q How does the Command Pattern (using Actions) use the 3 O-O characteristics? What is the benefit of each one?

How does Remote Control use the Pattern? Complete the table. Name in Command Pattern

How does Remote Control use the Pattern? Complete the table. Name in Command Pattern Invoker Command Concrete. Command Receiver execute( ) Name in Application

Abstract Superclass q What is an Abstract Class? a class with one or more

Abstract Superclass q What is an Abstract Class? a class with one or more abstract methods (method without an implementation) class must be declared "abstract" you cannot create an instance of an abstract class q Give example of an Abstract Class is Java. Abstract. Action, Abstract. List, Observable q Why use an Abstract Class? see following slides

Abstract Class q How would you use an Abstract Class?

Abstract Class q How would you use an Abstract Class?

Abstract Class for Money q Factor out common behavior and attributes needed by subclasses

Abstract Class for Money q Factor out common behavior and attributes needed by subclasses

Abstract Class for Money q Provide default implementations for methods if you don't like

Abstract Class for Money q Provide default implementations for methods if you don't like my equals then do it yourself! @Override equals(Object) {. . . }

Mouse. Adapter Abstract class provides default implementations of methods (convenience). Most of them do

Mouse. Adapter Abstract class provides default implementations of methods (convenience). Most of them do nothing. q Makes it easier to implement the interface. q

Abstract Classes Provide Behavior Observable, Abstract. List, Abstract. Action Abstract superclass providing methods and

Abstract Classes Provide Behavior Observable, Abstract. List, Abstract. Action Abstract superclass providing methods and attributes that implement useful behavior. Subclass can reuse this functionality or override it. Abstract. Action provides useful behavior to its subclasses.

Benefits of Abstract Superclass 1. 2. 3.

Benefits of Abstract Superclass 1. 2. 3.

Disadvantage of Abstract Superclass Are there any disadvantages or limitations on using an Abstract

Disadvantage of Abstract Superclass Are there any disadvantages or limitations on using an Abstract Superclass? 1. 2.

Abstract Superclass or Interface? Compare Abstract Class with Interface. Abstract Superclass Interface

Abstract Superclass or Interface? Compare Abstract Class with Interface. Abstract Superclass Interface

Patterns

Patterns

What Pattern Should We Use? q q General Problem: some resource needs to be

What Pattern Should We Use? q q General Problem: some resource needs to be shared by all objects. How can we guarantee that only one instance exists? Example: share a connection to a database. // Database. Manager should ensure we always // use the same connection Connection connection = Database. Manager. get. Connection( );

Draw a Class Diagram of Solution

Draw a Class Diagram of Solution

Changing Some Behavior q q General Problem: we have a reusable class but some

Changing Some Behavior q q General Problem: we have a reusable class but some methods need to change their behavior (algorithm) in different situations. Example: change the way a Container arranges Components. panel. set. Layout( new Grid. Layout(4, 3) ); panel. add( button 1 ); panel. add( button 2 ); . . .

Draw a Class Diagram Draw a class diagram of the parts of the Strategy

Draw a Class Diagram Draw a class diagram of the parts of the Strategy Pattern

Complete the Table How do Container and Layout. Manager use this pattern? Complete this

Complete the Table How do Container and Layout. Manager use this pattern? Complete this table. Name in Strategy Pattern Context Strategy Concrete. Strategy set. Strategy( ) do. Work( ) Name in this application

Give Another Example Give another example of the Strategy Pattern.

Give Another Example Give another example of the Strategy Pattern.

What Pattern Should We Use? General Problem: we want to modify or enhance some

What Pattern Should We Use? General Problem: we want to modify or enhance some behavior of a class, but we don't want to modify the class. q Example: how to add scroll bars to components q JText. Area textarea = new JText. Area( 8, 40); JScroll. Pane pane = new JScroll. Pane( textarea ); pane. set. Vertical. Scrollbar. Policy( JScroll. Pane. VERTICAL_SCROLLBAR_AS_NEEDED ): // add pane (not textarea) to container contentpane. add( pane );

Class Diagram of Decorator q Draw a class diagram of the decorator pattern.

Class Diagram of Decorator q Draw a class diagram of the decorator pattern.

Give Example of Observer Pattern Name in Observer Pattern Observer Subject (Observable) add. Observer(

Give Example of Observer Pattern Name in Observer Pattern Observer Subject (Observable) add. Observer( ) upate( ) [in Observer class] Name in Application

What Pattern Should We Use? General Problem: we have some legacy (existing) class we

What Pattern Should We Use? General Problem: we have some legacy (existing) class we want to use, but it doesn't have the correct interface. q Example: The Vector class creates an Enumeration (old), but our application wants an Iterator. q Enumeration<String> en = vector. elements( ); // process all the elements while ( en. has. More. Elements() ) { String s = en. next. Element( ); }

Draw a Class Diagram of Solution Design an Enumeration. Adapter<T> that implements Iterator<T>.

Draw a Class Diagram of Solution Design an Enumeration. Adapter<T> that implements Iterator<T>.

Being Adaptive q Problem: We want to put a Bank. Account object in the

Being Adaptive q Problem: We want to put a Bank. Account object in the Purse. But Bank. Account doesn't implement the Valuable interface. We don't want to change the Bank. Account class, either. Adapter get. Value()

Bank. Account. Adapter class Bank. Account. Adapter implements Valuable { private Bank. Account account;

Bank. Account. Adapter class Bank. Account. Adapter implements Valuable { private Bank. Account account; // dependency injection public Bank. Account. Adapter( Bank. Account acct ) { this. account = acct; } public int get. Value() { return account. get. Balance(); } }

Give Example of Observer Pattern Name in Observer Pattern Observer Subject (Observable) add. Observer(

Give Example of Observer Pattern Name in Observer Pattern Observer Subject (Observable) add. Observer( ) upate( ) [in Observer class] Name in Application

Improving Your Development Skills

Improving Your Development Skills

Improving Your Development Skills 1. Set Goals. 2. Be curious. What do you want

Improving Your Development Skills 1. Set Goals. 2. Be curious. What do you want to do? 3. Study good examples. n Apache Jakarta projects n Source. Forge projects (some good, some bad) n Object. Web. com, Java. Lobby, MSDN, . . . n many others 4. Practice, practice. n With discipline. . . design first, record your results. n Personal solutions log, blog, or wiki.

Improving Your Development Skills 5. Read.

Improving Your Development Skills 5. Read.

What We Didn't Cover 1. Frameworks. A structure for building applications. 2. Libraries. Reusable

What We Didn't Cover 1. Frameworks. A structure for building applications. 2. Libraries. Reusable software components. 2. Design principles and design patterns. n Gamma, et al. Patterns of Reusable Software n Head First books

Additional Review

Additional Review

Student (sorry this is so boring( q Implement the Student class described at right.

Student (sorry this is so boring( q Implement the Student class described at right. q Use the appropriate visibility for all members (attributes and methods). q Compare students by id q Write a to. String that can be used to produce output like this: q [48541111] Bill Gates <<interface>> T Comparable compare. To( other ) <T: : Student> Student id firstname lastname Student( first, last, id ) Student( first, last ) compare. To( student ) to. String( )

Write a Student. Reader class Purpose: reads student data from an Input. Stream. q

Write a Student. Reader class Purpose: reads student data from an Input. Stream. q Each line of data contains: student_id firstname 48541111 Bill Gates lastname Provides an Iterator<Student> to return one student object for each line of data read. Questions: 1. what methods does an Iterator have? 2. how do you show this in UML? 3. why use an Input. Stream? Why not a File? q

Student. Reader q <<interface>> Write the code T Iterator +has. Next( ) : boolean

Student. Reader q <<interface>> Write the code T Iterator +has. Next( ) : boolean + next( ) : T + remove( ) <T: : Student> Student - id - firstname - lastname Student( first, last, id ) compare. To( s ) "has a" Student. Reader( Input. Stream )

Draw a Sequence Diagram int sumdata( ) { // data should be a parameter,

Draw a Sequence Diagram int sumdata( ) { // data should be a parameter, but for simplicity. . . String data = new String( "3 5 8 13" ); Scanner in = new Scanner( data ); int sum = 0; while ( in. has. Next. Int( ) ) { int n = in. next. Int( ); sum += n; } return sum; }

Draw a Sequence Diagram public void run( ) { Coupon. Calc calc = new

Draw a Sequence Diagram public void run( ) { Coupon. Calc calc = new My. Coupon. Calc( ); Coupon. UI ui = new Coupon. UI( calc ); ui. run( ); }

Coupon Assistant q Why not design Coupon Assistant like this? Coupon. UI My. Coupon.

Coupon Assistant q Why not design Coupon Assistant like this? Coupon. UI My. Coupon. Calc - calc : My. Coupon. Calc + My. Coupon. Calc( ) public Coupon. UI( ) { calc = new My. Coupon. Calc( ); } public static void main(. . . ) { ui = new Coupon. UI( ); ui. run( );

What does this diagram mean? Why did we design the Coupon Assistant like this?

What does this diagram mean? Why did we design the Coupon Assistant like this? q What is the benefit of this? q Coupon. UI - calc : Coupon. Calc <<interface>> Coupon. Calc methods + run( ) Main main( ); calc = new My. Coupon. Calc( ); ui = new Coupon. UI( calc ); ui. run( ); My. Coupon. Calc + My. Coupon. Calc( )

JOption. Pane What is show. Confirm. Dialog ? Is it a static or instance

JOption. Pane What is show. Confirm. Dialog ? Is it a static or instance method? What is JOption. Pane. NO_OPTION int choice; choice = JOption. Pane. show. Confirm. Dialog( null, "Are you awake? ", "This is a Confirm Dialog", JOption. Pane. YES_NO_CANCEL_OPTION ); if ( choice == JOption. Pane. NO_OPTION ) JOption. Pane. show. Message. Dialog( null, "Liar!!");

Magic Numbers Is there any problem with this code? int choice; choice = JOption.

Magic Numbers Is there any problem with this code? int choice; choice = JOption. Pane. show. Confirm. Dialog( null, "Do you really want to quit? ", "Confirm Quit", JOption. Pane. OK_CANCEL_OPTION ); if ( choice == 0 ) System. exit( 0 ); How would you improve it?

Comparator Arrays. sort can accept a 2 nd parameter: Arrays. sort( array, comparator )

Comparator Arrays. sort can accept a 2 nd parameter: Arrays. sort( array, comparator ) array to sort will call comparator. compare(a, b) <<interface>> Comparator Why is this useful? Is compare( ) an instance or static method? +compare( a: T, b: T ) +equals( other ) T

Sort Students by First Name q. Write a Comparator that sorts students by first

Sort Students by First Name q. Write a Comparator that sorts students by first name. q. We can't use "Student. compare. To" because it already sorts Students by ID. /** Define a comparator for ordering students by first name */ public class Student. Comparator implements Comparator<Student> { int compare( Student a, Student b ) { // return + if after b, - if a before b, 0 if a and b have same order return a. get. First. Name( ). compare. To. Ignore. Case( b. get. First. Name() ); } }

Using the Comparator // Example: sort an array of students Student [ ] students

Using the Comparator // Example: sort an array of students Student [ ] students = Registrar. get. Students( ); Comparator<Student> comp = new Student. Comparator(); Arrays. sort( students, comp ); /** Define a comparator for comparing students by first name */ public class Student. Comparator implements Comparator<Student> { int compare( Student a, Student b ) { // return + if after b, - if a before b, 0 if a and b have same order return a. get. First. Name( ). compare. To. Ignore. Case( b. get. First. Name() ); } }

How to create using anonymous class Student [ ] students = Registrar. get. Students(

How to create using anonymous class Student [ ] students = Registrar. get. Students( ); Comparator<Student> comp = new Comparator<Student>( ) { // anonymous class definition for a Comparator<Student> object int compare( Student a, Student b ) { // return + if after b, - if a before b, 0 if a and b have same order return a. get. First. Name( ). compare. To. Ignore. Case( b. get. First. Name() ); } } ; // end of anonymous class and end of assignment ( ; ) Arrays. sort( students, comp );

Comparator Factory Method q. Create a static method in the Student class that creates

Comparator Factory Method q. Create a static method in the Student class that creates the comparator object (previous slide) using an anonymous class. q. Named the method get. Student. Name. Comparator( ) public class Student implements Comparable<Student> {. . . public static Comparator<Student> get. Student. Name. Comparator ( ) { return new Comparator<Student>( ) { public int compare. To( Student a, Student b ) { return a. get. First. Name(). compare. To( b. get. First. Name() ); } }; // end of the statement } // end of the method

Designing Classes Choose responsibilities and attributes. q Design the public "interface" of the class.

Designing Classes Choose responsibilities and attributes. q Design the public "interface" of the class. q Guides for class design: n cohesion - should be high n coupling to other classes - lower is better q Guides for interface: n completeness n convenience n clarity n consistency q

Big. Decimal Arithmetic q Write an average( ) method that computes the average of

Big. Decimal Arithmetic q Write an average( ) method that computes the average of an array of Big. Decimal objects. public Big. Decimal average( Big. Decimal [ ] x ) { Big. Decimal sum = new Big. Decimal( 0. 0 ); for( Big. Decimal value : x ) sum = sum. add(value); return sum. divide( new Big. Decimal( x. length ) ); }

Big. Decimal Arithmetic q Write a max( ) method that returns the maximum value

Big. Decimal Arithmetic q Write a max( ) method that returns the maximum value in an array of Big. Decimal objects, using only the compare. To method -- don't use Big. Decimal. max( ). public Big. Decimal max( Big. Decimal [ ] x ) { Big. Decimal max = x[0]; //. . . find the max in x[*] for( int k=1; k < x. length ; k++ ) //if ( x[k] > max ) max = x[k]; if ( x[k]. compare. To(max) > 0 ) max = x[k]; return max; }

Big. Decimal More Arithmetic Write a static sqrt( ) method for Big. Decimal objects

Big. Decimal More Arithmetic Write a static sqrt( ) method for Big. Decimal objects using Euler's method of finding square roots. q Find sqrt(2) accurate to 100 decimal places. q Let y = the value you want the square root of tolerance = allowed error in the answer Algorithm: This is useful practice for how to use method calls, but it throws a runtime x = 1. 0; // initial guess exception because some values repeat { have infinitely long decimal form. x 0 = x; You must use another form of Big. Decimal methods that has a x = ( x + y/x ) / 2; remainder. } until ( | x - x 0 | <= tolerance ) x is approximately the square root of y.

How to Write a Clone Method q Clone the Student class (next slide(

How to Write a Clone Method q Clone the Student class (next slide(

Deep copy of student public class Student implements Cloneable, Comparable { private String id;

Deep copy of student public class Student implements Cloneable, Comparable { private String id; private Date birthday; // date is mutable private List<Course> courses; public Object clone() { //1. make a new clone object and clone superclasses Student clone = (Student) super. clone( ); //2. copy all the atrributes to the clone. id = new String( this. id ); clone. birthday = this. birthday. clone(); clone. courses = new Array. List<Course>( ); for( course: this. courses ) clone. courses. add( course. clone() ); //3. return the clone return clone; }

Variable Scope and try - catch int a = in. next. Int( ); int

Variable Scope and try - catch int a = in. next. Int( ); int b = in. next. Int( ); try { int c = a / b; } catch ( Exception e) { System. err. println("bad division"); } System. out. println("a / b = " + c );