CC438 Object Oriented Software Design - PowerPoint PPT Presentation

1 / 138
About This Presentation
Title:

CC438 Object Oriented Software Design

Description:

Introduction to Object-oriented Design and UML. Programming ... Java programs are running quite fast these days. IntelliJ and Eclipse IDE are written in Java! ... – PowerPoint PPT presentation

Number of Views:390
Avg rating:3.0/5.0
Slides: 139
Provided by: udokrus
Category:

less

Transcript and Presenter's Notes

Title: CC438 Object Oriented Software Design


1
CC438Object Oriented Software Design
  • Lecturer Simon M. Lucas
  • GTA Pete Burrow
  • Autumn 2007

2
The Course Homepage
  • http//courses.essex.ac.uk/CC/CC438/
  • Information on lectures, classes and labs
  • Assessment details
  • Slides from lectures and classes
  • Bibliography
  • Pointers to further literature and tools

3
Course Overview
  • Introduction to Java programming
  • Introduction to Object-oriented Design and UML
  • Programming with Java Collections
  • Object-relational mapping and JDBC
  • Object-oriented databases db4o
  • Java Reflection API
  • Persistent Java and serialisation
  • Concurrency and threads
  • Dynamic UML models including use cases
  • Testing
  • Constraints
  • Design patterns
  • Other OO Languages Ruby and C

4
Literature See Web for Details
  • David Flanagan Java in a Nutshell , 2005.
  • Cay Horstmann, Object-Oriented Design Patterns,
    Wiley 2004.
  • Bruce Eckel Thinking in Java , 3nd Edition,
    Prentice Hall, 2002.
  • Bernd Bruegge and Allen H Dutoit Object-Oriented
    Software Engineering, 2004
  • Java Tutorial http//java.sun.com/docs/books/tuto
    rial/
  • If you want to buy other books
  • Check level and coverage of topics
  • Suggest buy (at least) one Java text book.

5
Tools
  • The version of Java used in this course is 5.0
  • also called 1.5
  • additional features compared to Java 1.4
  • Editors/Java IDEs
  • IntelliJ, NetBeans, Eclipse, JBuilder, BlueJ, etc
  • UML Tools
  • Fujaba and ArgoUML are available in labs
  • Fujaba is the recommended tool for use with cc438
  • Try free evaluation versions of other tool like
  • Borland Together Community Edition
  • IBM Rational rose

6
Acknowledgements
  • The original cc438 Advanced Java and Software
    Engineering course was originally developed
    jointly by Simon Lucas and Norbert Voelker
  • Norbert then significantly enhanced the course
    over a number of years
  • Simon added Ruby and C material for 2006
  • Dropped SE methodologies (Boehm, XP, Waterfall)
  • The course uses material from textbooks, in
    particular
  • Cay Horstmann Object-Oriented Design
    Patterns
  • Bruce Eckel Thinking in Java

7
Introduction to Programming in Java
  • Some slides derived from Horstmann OODP
  • See also our Java Intro Course for PG Students
    and Suns Java Tutorial
  • http//java.sun.com/docs/books/tutorial/java/index
    .html

8
Overview
  • Java classes and objects
  • example Hello, World 
  • Primitive types and wrapper classes
  • Control flow
  • conditionals, loops, exception handling,
    branching
  • Strings
  • Packages
  • Simple user input/output
  • JVM
  • Execution context
  • Programming Style

9
Why Java?
  • Popular OO programming language
  • Java programmers are in demand
  • Easier than C, less likely to corrupt memory
  • Good text books, popular in teaching
  • Runs on various platforms (Windows, Linux, ),
  • also profiles J2ME (mobile/wireless),
    JavaCard,
  • Exhaustive libraries
  • Web, GUI, network, maths, multimedia, drivers,
  • Lots of tools
  • Java programs are running quite fast these days
  • IntelliJ and Eclipse IDE are written in Java!
  • Very similar to Microsofts language C

10
  • public class Greeter
  • public Greeter(String aName)
  • name aName
  • public String sayHello()
  • return "Hello, " name "!"
  • private String name
  • visibility, names, types, parameter
    declarations, assignment and return statements

constructor
method
instance variable (attribute)
11
Classes
  • A Class is the basic unit of organisation in
    Java.
  • Attributes specify data
  • also called fields or instance/class variables
  • Methods specify behaviour
  • take the role of procedures or functions
  • In Java, classes may also have other classes
    defined within them
  • known as inner classes.
  • Methods can be seen as the services provided by
    the objects in that class.
  • Learn later about abstract classes and interfaces.

12
Objects
  • An instance of a class is called an Object.
  • You can think of a class as a template for a
    particular kind of objects.
  • In Java, every object instance of exactly one
    class.
  • The methods and attributes of a class by default
    belong to instances of a class
  • An object has its own copies of the instance
    variables defined in its class. You can think of
    each object having its own memory.
  • OO programs can be seen as objects telling each
    other what to do by sending messages.
  • A message is a request for a method call.

13
Class-Scoped Attributes Methods
  • The keyword static is used to define
    class-attributes and methods
  • these do not belong to a particular instance.
  • class-variables are shared between all objects of
    that class.
  • Class attributes and methods can be accessed
    without reference to an object of that class
  • x Math.PI
  • y Math.sqrt(x)
  • System.out.println(Hello World!)

14
Using Class Greeter
  • Construct new objects with new operator new
    Greeter("World")
  • Can invoke methods directly on a newly
    constructed object new Greeter("World").sayHello(
    )
  • More common to store object reference in a
    variable
  • Greeter worldGreeter new Greeter("World")
  • Then invoke methods on variable
  • String greeting worldGreeter.sayHello()

15
Class GreeterTest
  • public class GreeterTest
  • public static void main(String args)
  • Greeter worldGreeter new Greeter("World")
  • String greeting worldGreeter.sayHello()
  • System.out.println(greeting)
  • Method main() is called when program starts
  • main() is static it doesn't operate on any
    objects
  • there are no objects yet when main starts
  • main() constructs objects and invokes methods

16
Constructor Methods
  • A constructor is a method with the same name as
    its class.
  • Constructors do not declare an extra return type.
  • Constructors create and initialise objects.
  • If you write a class with no constructors, the
    compiler will automatically create a default
    constructor for you.
  • This only happens if your code has no
    constructors.
  • One constructor may be invoked from within
    another constructor.

17
Variables and Object References
  • Car myCar new Car(VD-12345, VW, 1998, 0)
  • Car oldCar myCar
  • Both variable myCar and oldCar refer to the new
    object created in the first line.
  • An object can be referenced by several variables.

Car
myCar
regNo VD-12345 make VW year 1998 speed
0
oldCar
18
Equality Testing
  • For primitive types, use
  • int x 10
  • int y 10
  • x y // equates to true
  • For objects, tests the reference
  • Integer x new Integer(10)
  • Integer y new Integer(10
  • Integer z x
  • y x // equates to false
  • y.equals(x) // equates to true
  • x z // equates to what?

19
Parameter Passing
  • Java uses call by value
  • If the value of a parameter is a reference, then
    the methods gets a copy of that reference. This
    can be used to modify the object referred to.
    Example
  • public void copyNameTo(Greeter other)
    other.name this.name
  • aGreeter.copyNameTo(bGreeter)
  • Java has no reference parameters
  • assigning new values to parameters has no effect
    once the method returns. Example
  • public void copyGreeterTo(Greeter other)
    other new Greeter(name)
  • aGreeter.copyGreeterTo(bGreeter) // bGreeter
    unchanged

20
The this Reference
  • Refers to implicit parameter of method call
  • Example Equality testing public boolean
    equals(Greeter other)     if (this other)
    return true    return name.equals(other.name)
  • Example Constructor public Greeter(String name)
    this.name name

21
Null
  • A null value means that a variable does not refer
    to any object.
  • if (errorInInput) Student nextStudent null
  • You can check if a variable refers to null.
  • This is useful as some functions return null if
    they are not able to return a valid object. For
    example, showInputDialogue returns null if the
    user hits the Cancel button.
  • String input JOptionPane.showInputDialogue(
  • Please enter account number)
  • if (input null)

22
Primitive Datatypes and Enumerations
  • Non-numeric primitive type boolean
  • Numeric primitive types
  • byte char short int long float double
  • Suffixes Llong, F float
  • Character constants a, \n, \u2121
  • Casts (int) x, (float) y
  • Math class has methods that operate on numbers
  • z Math.round(x)
  • User can define enumeration types
  • public enum StopLight red, amber, green

23
Enumeration Example
  • public class EnumTest
  • enum Light red, green, blue
  • public static void main(String args)
  • for (Light l Light.values())
  • System.out.println( l "
    \t " l.getClass())
  • C\smlgtjava test.java.EnumTest
  • red class test.EnumTestLight
  • green class test.EnumTestLight
  • blue class test.EnumTestLight
  • Note can also add methods to Enums
  • http//java.sun.com/j2se/1.5.0/docs/guide/language
    /enums.html

24
Wrapper Classes
  • Elements of the primitive data types are values.
    They are not objects (no identity!).
  • Sometimes it is necessary to use a value of a
    primitive type as it were an object.
  • Wrapper classes in java.lang
  • Boolean, Character, Integer, Long, Float, Double
  • There is also a class BigInteger of arbitrary
    precision integers.

25
Wrapper Classes Methods
  • Conversions
  • Integer x new Integer(42) // Integer from
    int
  • int i x.intValue() // int from Integer
  • Java 5.0 has automatic conversions
  • Integer x 42 int i x 5
  • autoboxing and auto-unboxing are only
    syntactic sugar, the byte code is the same as
    before
  • Other useful methods in class Integer
  • turn signed decimal number string into
    int-value
  • int v Integer.parseInt(argv0)
  • return String representation of Integer object
  • String s x.toString()

26
Control Flow
  • Iteration (looping)
  • for
  • while
  • do-while
  • Decision making (conditionals)
  • if-else
  • switch-case
  • Exception handling
  • try-catch-finally, throw
  • Branching
  • break, continue, label, return

27
Iteration for
  • for( initialiser condition iterator )
  • statement(s)
  • Variables can be declared locally in for loop
  • for (int i 1 i lt n i) . . .
  • // i no longer defined here
  • The condition is checked before executing the set
    of actions in the body of the loop.
  • If there is only one statement in the body of the
    loop, then the brackets can be omitted.

28
Iteration while and do...while
  • while ( condition )
  • statements
  • do statement(s)
  • while ( condition )
  • Java also supports recursive programming.
  • A method can call itself.

29
Conditional if .. else
  • if ( condition )
  • statement (s)
  • else
  • alternative statement(s)
  • Note that the else part is optional

30
break, continue and return
  • You can use an (unlabelled) break statement to
    terminate a switch, or a for, while or do-while
    loop.
  • The break statement terminates the innermost loop
    which contains it.
  • There is also a labelled version of the break
    statement that terminates nested loops/switches
    in one go.
  • You can use a continue statement to skip the rest
    of the current iteration of any loop.
  • A return statement exists the current method.
  • Two versions with return of a value, or without.

31
Exceptions I
  • Exception handling is a great way to control what
    happens when things go wrong.
  • String name null int n name.length() //
    ERROR
  • It is the Java Virtual Machine (JVM) that throws
    an exception. Unless there is a handler, the
    program will exit with a stack trace
  • Exception in thread "main" java.lang.NullPointe
    rException at Greeter.sayHello(Greeter.java25)
    at GreeterTest.main(GreeterTest.java6)

32
Checked and Unchecked Exceptions
  • Compiler tracks only checked exceptions.
  • For example, IOException is checked
  • Runtime exceptions like NullPointerException are
    not checked.
  • Generally, checked exceptions are thrown for
    reasons beyond the programmer's control.
  • typical non-existing files or other resources
    missing
  • Two ways of dealing with checked exceptions
  • declare them in the method header (means let
    the caller of this method deal with it)
  • or catch the exception
  • Note you can declare exceptions for main().

33
Exception Handling Code
  • Declaring exceptionspublic void read(String
    filename) throws IOException
  • Handling (catching) exceptions
  • try
  • statement(s)
  • catch (exceptiontype name)
  • statement(s)
  • finally
  • statement(s)
  • The finally clause is optional. Statements in
    the finally clause are always executed.

34
Strings I
  • Sequence of Unicode characters
  • length() method yields number of characters
  • "" is the empty string of length 0
  • different from null
  • charAt() method yields characters char c
    s.charAt(i)
  • substring() method yields substrings"Hello".subs
    tring(1, 3) is "el"
  • Use equals to compare strings if
    (greeting.equals("Hello"))
  • tests for identical object references
    ("Hello".substring(1, 3) "el") ... // NO!

35
Strings II
  • Use StringTokenizer to break string into
    substringsString countries "Germany,France,Ital
    y"StringTokenizer tokenizer new
    StringTokenizer(countries, ",")while
    (tokenizer.hasMoreTokens()) String country
    tokenizer.nextToken() ...
  • operator concatenates strings
  • If one argument of is a string, the other is
    converted into a string.
  • toString() method is applied to objects

36
Simple User Input and Output
  • Console input from System.in
  • Input dialogues
  • String input JOptionPane.showInputDialog( "H
    ow old are you?")
  • If user cancels, result is nullif (input !
    null) age Integer.parseInt(input)
  • Console output to System.out
  • Output messages
  • JOptionPane.showMessageDialog(null, "Hello!")

37
Command-Line Arguments
  • void main(String args)
  • args parameter of main() is initialized with
    command-line argument(s)
  • Examplejava GreeterTest Mars
  • args.length is 1args0 is "Mars"
  • Usually done to affect one particular invocation
  • for example by specifying -verbose in the command
    line
  • or to specify the names of input/output files

38
Some Programming Conventions
  • Variables, fields and methods start with
    lowercase, use caps for new words name,
    sayHello
  • Classes start with uppercase
  • Greeter, ArrayList
  • Constants all caps
  • PI, MAX_VALUE
  • Use get/set prefixes for getter/setter
    methods, but use is/set for boolean fields.
  • getName(), setName() isRegistered(),
    setRegistered(...)

39
Packages
  • Classes are grouped into packages.
  • Tree structure
  • Package names are dot-separated sequences.
  • java.util, javax.swing, essex.cc438.ass1
  • Full class name package name class name
  • java.util.ArrayList, javax.swing.JOptionPane
  • Package name must match subdirectory name
  • so class essex.cc438.ass1.Car must be in
    directory basedirectory/essex/cc438/ass1
  • Compile and run programs from base directory.
  • Add package statement to top of source file
  • classes without package name are in default
    package

40
Package/File Structure essex.cc438.ass1
41
Import from Packages
  • import java.util.ArrayList import static
    java.lang.Math.PI . . . ArrayList a
  • double r cos (PI theta)
  • Can import all classes from a package
    (careful!) import java.util.
  • But not from multiple packages import java..
    // NO
  • Beware class name clashes, for example between
    java.util.Date and java.sql.Date
  • Solution use full class name, i.e.
    java.util.Date
  • Never need to import java.lang.

42
Java Platforms
  • Platform independent (up to a point)

Hello.java
Hello.class
Hello.class
Hello.class
Hello.class
JVM LINUX
JVM IPAQ
JVM PC
43
The Java Virtual Machine
  • The compiler translates Java source to Java class
    files (byte codes).
  • A JVM maps byte codes to native machine
    instructions
  • A JVM loads classes on demand
  • Using a special class called a ClassLoader
  • The default one can be overridden
  • This may be done
  • once (Just In Time compilation)
  • or each time a byte code is executed (interpreted)

44
Execution Context
  • A method is executed by a Thread, which runs on a
    Java Virtual Machine (JVM)
  • A thread can be activated from many contexts.
  • the command line
  • graphical user interface
  • an applet in a web-page
  • or a servlet/JSP-engine on a web-server
  • If you design your software carefully, you can
    minimise (and even eradicate) the changes needed
    for different environments.

45
Hello World Servlet
  • package servlet.test
  • import java.io.
  • import javax.servlet.
  • import javax.servlet.http.
  • public class HelloText extends HttpServlet
  • public void doGet(
  • HttpServletRequest request,
  • HttpServletResponse response)
  • throws IOException, ServletException
  • response.setContentType("text/plain")
  • PrintWriter out response.getWriter()
  • out.println("Hello World")

46
HelloServlet Output
  • What a program does depends on the context in
    which it runs
  • This servlet was running in Tomcat on port 8080

47
Garbage Collection
  • In Java, there are no destructor methods for
    objects.
  • Instead, the JVM uses a garbage collector to
    reclaim heap space no longer needed
  • cause unreferenced objects
  • In rare cases, an object needs to free external
    resources before it is cleaned up
  • Java provides a finalize() method for specifying
    such customised clean-up operations.
  • Use with care, as you have no control over when
    it will be invoked (the Garbage Collector invokes
    it)

48
Speed of Java
  • Interpreted Java is SLOW
  • JIT Java is FAST (can rival C code)
  • Example output SML 2002
  • Running matrix multiplication of size 200 x 200
    for 1 repetitions
  • Done 360 ms elapsed
  • This speed rivals C
  • but the interpreted version is over thirty times
    slower

49
Practical Advice
  • Keep a link to the Java API doc. on your desktop.
  • Use a Java IDE (Intellij, Eclipse or Netbeans)
  • Develop your programs incrementally and
    iteratively
  • start with simple versions which you enhance
    gradually
  • use UML modelling for complicated programs
  • Perform unit testing
  • test each method of each class, keep the tests
  • Use javadoc for documenting your programs.
  • Adhere to Java code conventions
  • see for example http//java.sun.com/docs/codeconv/
  • at least ensure consistency

50
Summary
  • We have taken a brief tour of basic object
    oriented programming in Java. In particular, we
    have covered
  • classes and objects
  • basic types
  • control structures
  • Next week
  • UML introduction representation of classes
  • inheritance, interfaces, abstract classes,
    anonymous classes, nested classes and more
  • See you in the lab on Tuesday!

51
Introduction to UML

52
What is UML?
  • Unified Modelling Language (UML)
  • Standard notation for OOAD
  • currently version 1.5 but version 2.0 in the
    making
  • specification concentrates on syntax rather than
    semantics
  • Supported by tools
  • IBM Rational Rose, Borland Together, Fujaba,
    ArgoUML, Poseidon for UML, etc
  • Lots of literature
  • see cc438 web page for starters

53
UML Models
  • Static models describe structural aspects
  • class diagrams
  • (object diagrams)
  • (component diagrams)
  • (deployment diagrams)
  • Dynamic models describe behavioral aspects
  • use cases, use case diagrams
  • interaction diagrams
  • sequence diagrams
  • (collaboration diagrams)
  • statechart diagrams
  • activity diagrams

54
Basic UML Notation for Classes and Objects
Date
Date
day int month int year int
todayDate
day 31 month 12 year 2000
day 19 month 1 year 2001
set() getDay() getMonth() getYear() advance() befo
re()
todayDate
day 22 month 10 year 2004
xmasDay
55
Basic UML Class Notation
  • A class is drawn as a solid rectangle with three
    compartments for
  • class name, other general properties (top)
  • attributes (middle)
  • operations (bottom)
  • The attribute and/or the operation compartment
    may be suppressed.

56
Basic UML Style Guidelines
  • Class compartment
  • centred class names in bold face, start with a
    capital letter
  • name of abstract classes in italics
  • Attributes and operations
  • left justified, plain face attribute and
    operation names start with a lowercase letter.
  • Objects
  • instances names are centred, in plain face and
    underlined
  • no name means anonymous object

57
Advanced UML Class Notation
  • Type information
  • Scope of features
  • default is instance scope features with class
    (static) scope are underlined
  • Visibility of features
  • (public), (protected) or -(private).
  • protected means only subclasses have access
  • Default values, for example balance 0
  • Constraints in curly brackets

58
AdvancedClass Example Bennet
BankAccount
-nextAccountNumberInteger -accountNumberInteger
-accountNameString not null -balanceMoney
0 -overdraftLimitMoney
open(accountNameString)Booleanclose()Boolean
credit(amountMoney)Boolean debit(amountMoney
)Boolean viewBalance()Money getBalance()Mone
y -setBalance(newBalance Money)
  • Note (result) type
  • last in UML
  • first in Java

59
Introduction to Inheritance, Interfaces and
Abstract Classes

60
Inheritance
  • Inheritance means that a subclass incorporates
    structure and behaviour of from one or more
    parent classes (super classes).
  • A subclass inherits all features from its parents
  • Attributes, methods, relationships and meaning
  • Attributes can be hidden by redefinition (be
    careful!)
  • Methods can be overridden by redefinition
  • Some inherited features might not be accessible
  • In Java class A extends class B
  • a class can extend at most one other class
  • no multiple inheritance, single-rooted hierarchy
  • every class inherits from java.lang.Object

61
Shape
Separate Target Style
. . .
Polygon
Ellipse
Spline
Shape
Shared Target Style
Polygon
Ellipse
Spline
. . .
UML Notation for Inheritance
62
Inheritance Example Bruegge
Watch
time date
CalculatorWatch
setTime(tTime) setDate(dDate) getTime()Time get
Date()Date
calculatorState
enterCalcMode() inputNumber(n)
63
Interfaces
  • An interface is a special kind of class.
  • An interface cannot be instantiated.
  • It contains only abstract methods and constants.
  • A class can implement an interface
  • this means it provides methods as required by
    that interface
  • methods with the same name and the same number
    and type of arguments
  • A class may implement more than one interface.
  • See Java API for many examples of interfaces
  • See also lectures on Java Collections Framework.

64
UML Interface Notation
interface Icon
interface EventListener
getIconHeight()getIconWidth()paintIcon()
javax.swing.AbstractAction
FormView
ActionListener
65
Abstract Classes and Methods
  • An abstract class cannot be instantiated
  • abstract class
  • You cannot create objects belonging to such a
    class.
  • An abstract class can contain abstract and
    non-abstract methods.
  • public abstract double area ()
  • Abstract classes are useful to define
    incomplete classes
  • Made complete in concrete subclasses. These need
    to implement all abstract methods.
  • Abstract methods can only be defined in abstract
    classes and in interfaces.

66
Shapes Example
  • A simple OO modelling example
  • Model some geometric shapes
  • Uses abstract classes and interfaces
  • Note do not confuse class cc438.exercises.Shape
    with the interface java.awt.Shape

67
Geometric Shapes
  • Each shape has a central position
  • For each shape we wish to compute
  • Area
  • Perimeter
  • Later, well also want to draw them
  • Specific shapes circle, rectangle, diamond

68
Shape Class Requirements
  • Have attributes for position (x and y coord)
  • Have methods for computing the area and the
    perimeter
  • Q. How can we do this, without knowing the
    details of what kind of shape we have?
  • A. We cant so just define the method
    signatures instead.
  • This leads us to the concept of an abstract class
    one which cannot be instantiated
  • Classes which can be instantiated are called
    concrete classes these are the default

69
Shape Class Diagram

70
Visibility Modifiers in Java
  • Public world access
  • Protected may be accessed by subclasses and
    other classes within the same package
  • Private access only by this class
  • Default package access only
  • Java does not distinguish between read/write
    access for visibility

71
Shape Class
  • package cc438.examples
  • public abstract class Shape
  • protected double x
  • protected double y
  • public abstract double area()
  • public abstract double perimeter()

72
Circle Class Diagram

Shape double x double y double
area() double perimeter() String toString()
Circle double r Circle()
Circle (double x, double y, double r) double
area() double perimeter()
73
Class Circle in Java
  • package cc438.examples
  • public class Circle extends Shape
  • protected double r
  • public Circle() this(0, 0, 1)
  • public Circle(double x, double y, double r)
  • this.x x this.y y this.r r
  • public double area()
  • return Math.PI r r
  • public double perimeter()
  • return Math.PI 2 r

74
Notes on Circle
  • Note the provision of a default constructor
    provides an easy way of making new circles
  • this( 0, 0, 1 ) calls the second constructor
  • which then sets up the attributes of this newly
    created circle to the arguments passed to the
    constructor
  • The position of the Circle (x,y) is inherited
    from the Shape superclass, which Circle extends.
  • Circle can be a concrete class because it
    provides implementations of Shapes abstract
    methods.

75
Shape Test
  • package cc438.examples
  • public class ShapeTest
  • public static void main(String args)
  • System.out.println( new Circle() )

76
Shape Test Output 1
  • C\srcgt java cc438.examples.ShapeTest
  • cc438.examples.Circle_at_3e86d0
  • Note that all classes have java.lang.Object as
    their ultimate superclass.
  • The Object class defines a method toString()
  • This prints a string representation of the
    object.
  • The default implementation just prints the object
    reference
  • Override this to provide more useful information!

77
More useful toString() method
  • Now add this method to the Shape class
  • public String toString()
  • return "Shape at " x " , " y " "
  • "\n area " area()
  • " perimeter " perimeter()
    "\n"
  • New output from the ShapeTest program
  • Shape at 0.0 , 0.0
  • area 3.141592653589793 perimeter
    6.283185307179586

78
Drawable Shapes
79
Drawable Circle
  • Java graphics can be complicated!
  • Here we provide the minimum of what you need to
    know
  • A Graphics object has methods for displaying
    various geometric figures
  • You can get this from a Component
  • A Component can be displayed in a Window, Frame
    or Applet all subclasses of Container
  • Container objects have a Layout which determine
    how components are positioned
  • Simple but useful BorderLayout

80
Drawable Interface
  • We begin with a very simple interface
  • This describes the methods (in this case just
    one) that must be implemented by any object that
    should be considered drawable in our application.
  • package cc438.examples
  • public interface Drawable
  • public void draw(java.awt.Graphics g)

81
DrawableCircle
  • This class demonstrates how to subclass Circle
  • Thereby inheriting the instance variables
  • And calling the superclass constructor (super())
    to set them up
  • Also shows how to use the java.awt.Graphics
    object to draw itself (using the fillOval()
    command)
  • See the lab session for a class DrawTest that
    uses DrawableCircle.

82
Drawable Circle Class Diagram

83
  • package cc438.examples
  • import java.awt.
  • public class DrawableCircle extends Circle
    implements Drawable
  • Color c
  • public DrawableCircle(Color c)
  • super()
  • this.c c
  • public DrawableCircle(double x, double y,
    double r, Color c
  • super(x, y, r)
  • this.c c
  • public void draw(Graphics g)
  • g.setColor( c )
  • g.fillOval((int) (x-r), (int) (y-r),
    (int) (2r), (int) (2r) )

84
Forms of Inheritance
  • Two basic forms
  • interface inheritance parent is abstract (class
    or interface).
  • implementation inheritance child inherits
    methods or fields from concrete parent class
  • In Java, implementation inheritance is restricted
    to a single parent.
  • but a class can implement many interfaces.
  • See the book by B. Meyer for a comprehensive
    discussion of different forms of inheritance.

85
Inheritance between Interfaces
interface EventListener
interfaceActionListener actionPerformed (e
ActionEvent)
86
Multiple Inheritance
  • In UML, a class can have more than one parent.
  • There can be no cycles in an inheritance lattice.
  • Multiple inheritance is allowed in UML
  • conflicts can be resolved by specifying an
    ordering of parents or by prefixing inherited
    feature name with the names of the appropriate
    parent class.

Watch
Calculator
CalculatorWatch
87
Object Composition as an Alternative for
Inheritance
  • Implementation inheritance couples parent classes
    and subclasses very closely.
  • Often, it is preferable to assemble new classes
    from old classes by using objects as fields.
  • instead of inheriting methods, the new class can
    delegate requests to these fields
  • Object composition can be used as a workaround
    that makes up for the absence of multiple
    implementation inheritance in Java.

88
Composition/ Delegation
Calculator
Watch
calculatorState
watchState
enterCalcMode()inputNumber(n)
setTime(t) getTime()
CalculatorWatch
watch Watch calc Calculator setTime(t) getTime()
enterCalcMode() inputNumber(n)
89
Inheritance and Composition Combined
Calculator
Watch
calculatorState
watchState
enterCalcMode()inputNumber(n)
setTime(t) getTime()
CalculatorWatch1
CalculatorWatch2
watch Watch setTime(t) getTime()
calc Calculator enterCalcMode() inputNumber(n)
90
Static Typing, Method Overriding, Late Binding
  • Objects belong to exactly one class, but can
    conform to several types.
  • Static typing ensures at compile time that
    objects support operations.
  • Child operations override parent operations with
    the same signature. At runtime, the operation is
    chosen according to the class of the object.
  • This is known as late binding. It is used in
    languages such as Java, C and Eiffel.
  • Using overriding of methods is an example of
    polymorphism
  • code that works with more than one type.

91
public class Parent void whoami ()
System.out.println("I am a parent") public
class Child extends Parent void whoami ()
System.out.println("I am a
child") public class ParentTest public
static void main(String args) Parent
p new Parent() p.whoami() Child c
new Child() c.whoami() Parent q
new Child() q.whoami()
92
Invoking Superclass Methods Constructors
  • Can not access private features of super classes.
  • Superclass methods
  • if a subclass overrides a parent method, use
    super keyword to force method call of parent
  • do not forget the super statement!
  • Superclass constructors
  • Call to super must be first statement in subclass
    constructor
  • If a subclass constructor does not call super
    explicitly, then the superclass must have a
    constructor without parameters
  • calling super-classes happens before
    initialisation and execution of rest of
    constructor body.

93
Example for using super
  • public class Manager extends Employee
  • public Manager(String aName)
  • super(aName)
  •    bonus 0
  •    public double getSalary()          return
    super.getSalary() bonus    
  • ...

94
Hiding Attributes and Class Methods
  • An attribute in a subclass hides an attribute
    with the same name in a parent class
  • even if attribute has different type
  • hiding of attributes is in general not
    recommended
  • be careful not to accidentally hide attributes
  • the parent class attribute can still be accessed
    using the keyword super
  • A static method in a subclass hides a static
    method with the same name in a parent class.
  • Can still call the hidden method by prefixing
    the method name with the class name.

95
Exception Class Hierarchy
96
Catching Exception by Class
  • try code that may throw exceptionscatch
    (ExceptionType1 exception1) handler for
    ExceptionType1catch (ExceptionType2
    exception1) handler for ExceptionType2
  • Can catch by superclass catch (IOException
    excpt) catches FileNotFoundException
  • Users can define their own exception classes.

97
final Classes and Methods
  • A class can be declared final if no subclasses
    are designed or required.
  • can be used as a precaution to enhance security
  • the methods of a final class can not be
    overridden
  • classes can not be defined both abstract and
    final
  • A method can be declared final to prevent
    subclasses from overriding or hiding it.
  • less restrictive than making a whole class final
  • unnecessary for private methods/ methods in final
    classes
  • a final method can not be declared abstract
  • Remember meaning of final for attributes?

98
Closing Remarks
  • Inheritance is a powerful concept
  • parent classes contain shared attributes/code
  • subclasses provide alternatives
  • Overriding a method allows changing the method
    implementation for sub class objects
  • Interface definition need to be chosen carefully
  • extending an interface later might break existing
    code.
  • Do not over-use inheritance
  • strong coupling between parent and child classes
  • often preferable to use composition/delegation
    instead

99
Java Collections Framework
  • See also
  • http//java.sun.com/docs/books/tutorial/collection
    s/
  • http//java.sun.com/docs/books/tutorial/java/javaO
    O/generics.html
  • http//java.sun.com/developer/Books/javaprogrammin
    g/corejava/

100
Introduction
  • Library for dealing with groups of objects
  • Defines
  • interfaces
  • abstract classes
  • concrete classes
  • Generic collections since Java 5.0
  • These lectures can only give an overview
  • check out online collection doc. for more details

101
Introduction to Generics
  • Generic types make it possible to parameterise
    classes with a type. In particular, you can
    indicate the element type of collections
  • List ltStringgt list new ArrayListltStringgt()
  • Generic methods can be written using type
    variables and wildcard types.
  • Advantages of generics
  • improved readability as fewer casts are required
  • improved safety/less runtime errors as the
    compiler can catch more errors
  • The Java compiler erases information related to
    type parameters and arguments (unlike C).

102
General Remarks
  • Unlike arrays, collections can only hold objects
  • elements of primitive types such as int need
    wrapping
  • due to auto-boxing/unboxing, this is not such a
    bother
  • Some interfaces have optional methods which do
    not need to be implemented in classes.
  • unsupported methods throw at runtime
    UnsupportedOperationException
  • for example Collections.add(), see API doc for
    details
  • Thread-safety will be considered in a later
    lecture
  • Legacy collections that do not specify the type
    of elements are also called raw types
  • Type safety warnings for code with old
    collections.

103
Main Collection Interfaces
Collection
Map
List
Set
SortedMap
Queue
SortedSet
104
Interface Collection
  • Represents a general group of elements
  • abstraction over lists, sets, queues, multisets,
    etc.
  • J2SDK does not implement this interface directly,
    only sub-interfaces
  • Set, List, Queue
  • Users can define own sub-interfaces and
    implementations.
  • Java interfaces can not specify or enforce the
    semantics of methods
  • but implementations should be correct with
    respect to the intended meaning, i.e. for a list
    x, x.add(i,y) should insert the element y at
    position i.

105
  • public interface Collection ltEgt
  • // Basic operationsint size() boolean
    isEmpty() boolean contains(Object element)
    boolean add(E element) boolean
    remove(Object element) Iterator ltEgt
    iterator()
  • // Bulk operations
  • // Array operations

106
Collection Basic Operations
  • size(), isEmpty(), contains(Object x)
  • as expected
  • add(E x)
  • add an object to a collection
  • returns true if collection has changed
  • the type of element x is E
  • remove(Object x)
  • removes a single instance of the element
  • returns true if collection has changed, false
    otherwise
  • contains(x) and remove(x) throw at runtime a
    ClassCastException if the element x is of the
    wrong type.

107
Enhanced for-loop
  • public static int sum (Collection ltIntegergt xs)
  • int result 0
  • for (int x xs) result x
  • return result
  • Can also be used for arrays, and for classes
    implementing the Iterable interface.
  • Shorter, more readable code
  • But only works for loops which do not need
    indexed access via an iterator.
  • Also called for each loop, similar to C.

108
interface Iterator ltEgt
hasNext() booleannext() Eremove() void
  • Iterator traverses elements of an collection
  • hasNext() returns true if there are more
    elements
  • next() returns next element or throws
    NoSuchElementException
  • remove() removes the last element returned by
    next() or throws an exception (optional
    operation)

109
Example Iterator
static void filterEven (Collection ltIntegergt c)
for (Iterator ltIntegergt i c.iterator()
i.hasNext() ) if (!isEven(i.next()))
i.remove()
  • This code works for any collection (sets, lists,
    sorted lists) of integers (polymorphic).
  • Can be adapted easily to other boolean functions
    instead of isEven.

110
Collection Bulk Operations
// Bulk operations boolean containsAll
(Collection lt?gt c) boolean addAll (Collection
lt? extends Egt c) boolean removeAll
(Collection lt?gt c) boolean retainAll
(Collection lt?gt c) void clear ()
  • clear() removes all elements
  • The wildcard type ? matches any type.
  • The bounded wildcard type (Collection lt?
    extends Egt c)
  • means that the elements of the collection c have
    to belong to subtypes of E.

111
Collection Array Operations
// Array Operations Object toArray()
Object toArray(Object a)
  • Bridge between collections and arrays
  • The first form creates a new array.
  • The second form uses an existing array. If that
    is not large enough, it creates a new array.
  • Examples Object a c.toArray()String a
    (String) c.toArray(new String0)

112
Assumptions about Elements
  • The JDK provides various implementations of
    extensions of interface Collection.
  • Element classes have to provide
  • a proper equals() method, so that equality of
    collections behaves as expected
  • for implementations based on hash arrays, a
    proper hashCode() method, so that the
    distribution to buckets is fair see lab
    exercise!
  • an ordering for sorted implementations.

113
Interface Set
  • Models finite mathematical sets
  • no duplicates
  • order irrelevant two sets are equal if they
    contain the same elements
  • meaning of operations is as for sets
  • Inherits methods from interface Collection
  • J2SE provides various implementations of this
    interface including
  • HashSet, LinkedHashSet, TreeSet

114
Maths Interface Set
  • equality ()
  • is_element (?)
  • subset_or_eq (?)
  • union (?)
  • intersection (?)
  • set difference (-)
  • cardinality (size)
  • equals
  • contains
  • containsAll
  • addAll
  • retainAll
  • removeAll
  • size

Collection methods like addAll() are destructive
they change the objects to which they are
applied. Note that addAll() works also with
non-set arguments.
115
HashSet and LinkedHashSet
  • Implement interface Set as a hash table
  • efficient, general-purpose implementations
  • basic operations (add, remove, contains and size)
    perform in constant time as long as capacity not
    exceeded
  • default initial capacity/load-factor, can be set
    explicitly
  • includes all optional methods
  • HashSet does not fix order of elements in
    iterator
  • might even change over time
  • LinkedHashSet orders elements according to the
    order in which they were inserted
  • slightly more expensive than HashSet as it also
    keeps a linked list of elements

116
TreeSet
  • Implements Set in a sorted, balanced tree
  • includes all optional methods
  • elements are sorted according to natural order
    (Comparable) or a comparator provided at set
    creation time.
  • Slower than HashSet for most applications
  • log(n) time for basic operation (n size of
    set)
  • Useful for applications where
  • ordering of elements is important
  • collection must not contain duplicates

117
Example TreeSet
  • Set ltStringgt myFriends new HashSet ltStringgt
    ()
  • String peter Peter
  • String mary Mary
  • myFriends.add(peter)
  • myFriends.add(mary)
  • myFriends.add(peter)
  • System.out.println(My friends " myFriends)
  • What would be the result if we added Peter and
    Marydirectly to myFriends, i.e. without
    assigning these strings to variables peter/mary?

118
Worked Exercise
  • Write a Java program that
  • defines a new set called yourFriends with
    elements Paul, Lucy and Mary
  • defines a new set called commonFriends consisting
    of our common friends
  • defines a new set called allFriends consisting
    of all of our friends.
  • Use bulk operations whenever possible.

119
Solution
  • Set ltStringgt yourFriends new HashSet ltStringgt
    ()
  • yourFriends.add(Paul)
  • yourFriends.add(Lucy)
  • yourFriends.add(Mary)
  • Set ltStringgt commonFriends new HashSetltStringgt
    (myFriends)
  • commonFriends.retainAll(yourFriends)
  • Set ltStringgt allFriends new TreeSetltStringgt
    (myFriends)
  • allFriends.addAll(yourFriends)
  • System.out.println("Common " commonFriends)
  • System.out.println("All " allFriends)

120
Programming to Interfaces
  • The interface implementation class is only
    referred to during object creation.
  • Set students new HashSet ()
  • Using only interface methods makes program code
    implementation independent.
  • loose coupling can replace implementation
    classes
  • upcast ensures only interface methods are
    called.
  • only object creation has to be modified if
    interface implementation is changed
  • Set students new TreeSet ()
  • This is an example of polymorphism
  • the class of objects and the executed program
    code (methods) are unknown before runtime

121
List Interface
  • Models finite sequences.
  • elements are ordered
  • duplicates are allowed
  • meaning of operations is as for lists
  • Provides further
  • position-based methods (indexed access)
  • enhanced iteration which allows modifying the
    current element
  • Two lists are equal if they have the same
    elements, in the same order.

122
ListltEgt Methods not in Collection ltEgt
  • void add (int index, E element)
  • boolean addAll (int index, Collection lt? extends
    Egt c)
  • E get (int index)
  • E set (int index, E element)
  • int indexOf (Object o)
  • int lastIndexOf (Object o)
  • ListIterator ltEgt listIterator()
  • ListIterator ltEgt listIterator(int startIndex)
  • Object remove(int index)
  • List ltEgt subList (int from, int to)

123
ListIterator ltEgt
public interface ListIterator extends Iterator
void add (E element) boolean hasNext()
boolean hasPrevious() E next()
int nextIndex() E previous()
int previousIndex() void remove()
void set (E element)
124
Remarks on List and ListIterator
  • Collection methods
  • add() and addAll() append to the end of a list
  • addAll(x) uses x.iterator() for order
  • remove() removes only first occurrence
  • Position-based methods
  • indexing starts at 0
  • ListIterator.remove() removes the last element
    returned by next() or previous().
  • ListIterator.set(x) overwrites the last element
    returned by next() or previous().
  • ListIterator.add(x) inserts x before cursor.

125
Views
  • The method call sublist(fromIndex,toIndex)
    provides a view of the portion of a list between
    fromIndex (inclusive) and toIndex (exclusive).
  • The object returned by x.sublist(a,b) implements
    interface List, but it is not an independent copy
    of x.
  • In fact, changes to the list object returned by
    sublist() change the original list.
  • The Collection API has different kinds of views
  • read-only, modifiable, resizable, synchronized
  • Methods that return views include
  • Arrays.asList(), Map.keySet(), Map.values(),
    Map.entrySet(), unmodifableList(), nCopies()

126
List Implementations
  • JDK provides
  • ArrayList (based on a resizable array)
  • LinkedList (based on a double-linked list)
  • Vector (also resizable array, synchronized)
  • and others
  • ArrayList strong points
  • fast random-access to elements
  • fast insertion of elements at the end
  • LinkedList strong points
  • fast sequential access
  • fast removal/ insertion of elements during a list
    iteration

127
Queues
  • public interface QueueltEgt extends CollectionltEgt
  • E element() // top element, throw exception if
    fail
  • E peek() // top element, return null if fail
  • boolean offer(E o) // add element, return
    false if fail
  • E poll() // remove top element, return null if
    fail
  • E remove() // remove top element, throw
    except. if fail
  • Queues are typically FIFO (first-in/first-out)
  • notable exception priority queues
  • Can have fixed capacity (bounded queues)
  • Implementations LinkedList, PriorityQueue,

128
Map Interface
  • A map holds key-value pairs
  • no duplicate keys
  • Can be represented as set of key-value pairs
    without duplicate keys
  • Map does not extend Collection
  • cleaner as a separate concept
  • Three sorts of operations
  • altering, querying and alternative views

129
interface MapltK,Vgt clear() void containsKey(key
Object) boolean containsValue(valueObject)
boolean entrySet() Set ltMap.EntryltK,Vgtgt get(keyO
bject) V isEmpty() boolean keySet() Set
ltKgt put(keyK, valueV) V putAll(tMaplt? extends
K, ? extends Vgt) void remove(keyObject)
V size() int values() CollectionltVgt
130
Map Operations
  • Modification operations
  • put(), putAll(),
  • remove(), clear()
  • do not add a Map object to itself as a key or
    value.
  • Query operations
  • get(), containsKey(), containsValue(), size(),
    isEmpty()
  • Views
  • keySet(), values(), entrySet()
  • Note that entrySet() returns a set of Map.Entry
    objects.

131
equals(o Object) boolean getKey()
K getValue() V hashCode() int setValue(value
V) V
interfaceMap.Entry ltK,Vgt
  • Each Map.Entry object corresponds to a key-value
    pair in the underlying map.
  • You can change and query a map object by
    iterating through its Map.Entry set. The iterator
    becomes invalid if the map is changed outside the
    setValue() method.

132
Map Implementations
  • HashMap (requires hashCode())
  • fast, general purpose implementation
  • LinkedHashMap
  • similar to HashMap but additionally keeps
    elements in the order in which they were
    inserted.
  • TreeMap (requires order on elements)
  • is mainly useful if you need to transverse the
    map in sorted order.
  • All these implementations are cloneable
  • so are HashSet, TreeSet, ArrayList and
    LinkedList.
  • JDK offers several more Map implementations.

133
interfaceComparableltTgt
compareTo(T o) int
  • J2SE classes which have a natural ordering
    implement Comparable.
  • The call x.compareTo(y) returns
  • a negative integer, if x is less than y
  • a positive integer, if x is greater than y
  • 0, otherwise
  • This is the default ordering for sorting.
  • what if we want to sort with respect to another
    order?

134
interfaceComparator ltTgt
compare(o1 T, o2 T) int
  • Given a comparator c, c.compare(x,y) returns
  • a negative integer, if x less than y
  • a positive integer, if x greater than y
  • 0, otherwise
  • Note (c.compare(x,y) 0) or (x.compareTo(y)
    0) do not necessarily imply x.equals(y)
  • Use a Comparator object if
  • class does not implement Comparable
  • compareTo() gives wrong behaviour.

135
Comparator Example
  • class StringCompare implements
    ComparatorltStringgt
  • public int compare(String x, String y)
  • return (x.toLowerCase()).compareTo(y.toLower
    Case())
  • StringCompare c new StringCompare()
  • System.out.println("abc.compareTo(abc , Abc) "
    "abc".compareTo("Abc"))
  • System.out.println("cmp.compare(abc , Abc) "
    c.compare("abc , "Abc"))

136
Utility Class Coll
Write a Comment
User Comments (0)
About PowerShow.com