Title: COSC 3P40 Advanced ObjectOriented Programming
1COSC 3P40Advanced Object-Oriented Programming
- Instructor Michael Winter
- Office J323
- Office Hours Tue Thu 1000am noon
- email mwinter_at_brocku.ca
- Webpage www.cosc.brocku.ca/Offerings/3P40
2- Course Description (Brock Calendar)
Advanced
object-oriented programming techniques such as
graphical user interfaces, animation, sound,
music, networking, parallelism, client-server and
XML using game design as an example. Topics in
object-oriented program design including UML and
design patterns. Introduction to advanced Java
APIs such as awt, swing, io, nio, sound, net and
xml. - Prerequisites COSC 2P03 (minimum 60 percent) and
COSC 2P90 (minimum 60
percent). - Java Java 1.5 or greater and JCreator
- It is your responsibility to ensure that your
program runs on the lab equipment. - course procedures
- plagiarism
- MOSS
3Textbooks
- Main Course Material
- SLIDES and NOTES (available through the webpage)
- Supplemental Texts
- Developing Games in Java, D. Brackeen, New
Riders (2003), ISBN 1-5927-3005-1 - Object-Oriented Software Development Using Java,
second edition, Xiaoping Jia, Addison Wesley
(2002), ISBN 0-201-73733-7
4Course Work
- Marking Scheme
- Programming Assignments (4x15) 60
- Final Exam 40
- Programming Assignments
Number Due Late - 1 Feb 02 _at_ 100 pm Feb 04 _at_ 100 pm
- 2 Feb 23 _at_ 100 pm Feb 25 _at_ 100 pm
- 3 Mar 16 _at_ 100 pm Mar 18 _at_ 100 pm
- 4 Apr 06 _at_ 100 pm Apr 08 _at_ 100 pm
5Course Outline
6- Assignments will be available on-line.
Assignments will be returned via room J333 at the
times posted. - Assignments are due at the times specified above
and will be accepted late until the indicated
time, subject to a penalty of 25. After the late
period, assignments will not be accepted. - A mark of at least 40 on the final exam is
required to achieve a passing grade in this
course. No electronic devices and especially no
calculators will be allowed in the examination
room. - Assignments will be carefully examined regarding
plagiarism. Cases of suspected plagiarism will be
dealt with according to the University
regulations and Departmental procedures. - Consideration regarding illness for assignment
submission or test dates will only be considered
if accompanied with the completed Departmental
Medical Excuse form.
7Design principles
- Design principles in this course and used by the
design patterns - Use abstraction whenever possible
- introduce (abstract) superclass (or interfaces)
in order to implement or define common behavior - nothing should be implemented twice
- Program to an interface, not an implementation
- Favor composition over inheritance
- delegation
- Design for change and extension
8Classes
- ClassModifiers class ClassName
- extends SuperClass
- implements Interface1, Interface2,
- ClassMemberDeclarations
-
- Class modifiers
- visibility package versus public
- abstract
- final
- extends clause specifies the superclass
- implements clause specifies the interfaces being
implemented
9Class members
- Class (static) members
- one occurrence for entire class
- shared access by all instances
- if visible, accessed via class name
- public static void main(String args)
- Member modifiers
- public versus protected versus package versus
private - abstract
- final
- synchronized (method)
- native (method)
- volatile (field)
- transient (field)
10Inheritance
- Parent/child, superclass/subclass
- Instances of child inherit data and behaviour of
parent - implements
- inheritance of specification
- extends
- subclassing
- inheritance of code and specification
- overriding
- polymorphism
- Subclass versus subtype
- substitutability
- Subclass as an extension of behavior
(specialization) - Subtype as a contraction of value space
(specialization)
11Subtypes
- a subclass extends the capability of its
superclass the subclass inherits features from
its superclass and adds more features - every instance of a subclass is an instance of
the superclass - each class defines a type
- Definition Subtype
- Type T1 is a subtype of type T2 if every
legitimate value of T1 is also a legitimate value
of T2. In this case, T2 is a supertype of T1. - Substitutability of subtypes
- A value of a subtype can appear wherever a value
of its supertype is expected.
12Overriding versus Overloading
- Overloading
- methods
- same name, different signatures
- same class or subclass
- effect multiple methods with same name
- do not overuse (readability of programs)
- overloading should be used only in two
situations - When there is a general, non-discriminative
description of the functionality that fits all
the overloaded methods. - When all the overloaded methods offer the same
functionality, with some of them providing
default arguments. - Overriding
- instance methods
- same name, signature and result type
- in subclass
- effect replacement implementation
- access superclass version via super
13Forms of inheritance
- Inheritance for specification
- parent provides specification
- abstract classes
- interfaces
- behaviour implemented in child
- subtype
- Inheritance for extension
- adding behaviour
- subtype
- Inheritance for specialization
- child is special case
- child overrides behavior to extend
- subtype
14 - Inheritance for construction
- inherit functionality
- ad hoc inheritance
- not a subtype
- use composition
- Inheritance for limitation
- restricting behaviour
- not subtype
- use composition
- Inheritance for combination
- combining behaviours
- multiple inheritance
- only through interfaces in Java
15Inheritance for Specification Java
interfaceCh.8.4, Budd Understanding
Object-Oriented Programming with Java
- interface ActionListener
- public void actionPerformed (ActionEvent e)
-
- class CannonWorld extends Frame
-
- // a fire button listener implements the
action - // listener interface
- private class FireButtonListener implements
ActionListener - public void actionPerformed (ActionEvent e)
- // action to perform in response to button
press -
-
16Inheritance for Specification abstract
classCh.8.4, Budd Understanding Object-Oriented
Programming with Java
- public abstract class Number
- public abstract int intValue()
- public abstract long longValue()
- public abstract float floatValue()
- public abstract double doubleValue()
- public byte byteValue()
- return (byte) intValue()
- public short shortValue()
- return (short) intValue()
17Inheritance for ExtensionCh.8.4, Budd
Understanding Object-Oriented Programming with
Java
- class Properties extends Hashtable
-
- public synchronized void load(InputStream in)
- throws IOException
- public synchronized void save(OutputStream out,
- String header)
- public String getProperty(String key)
- public Enumeration propertyNames()
- public void list(PrintStream out)
18Inheritance for Specialization
- public class MyCar extends Car
-
- public void startEngine()
- motivateCar()
- super.startEngine()
-
-
19Inheritance for Construction Ch.8.4, Budd
Understanding Object-Oriented Programming with
Java
- class Stack extends LinkedList
- public Object push(Object item)
- addElement(item) return item
- public boolean empty()
- return isEmpty()
- public synchronized Object pop()
- Object obj peek()
- removeElementAt(size() - 1)
- return obj
-
- public synchronized Object peek()
- return elementAt(size() - 1)
20Inheritance for LimitationCh.8.4, Budd
Understanding Object-Oriented Programming with
Java
- class Set extends LinkedList
- // methods addElement, removeElement, contains,
- // isEmpty and size are all inherited from
LinkedList - public int indexOf(Object obj)
- System.out.println(Do not use Set.indexOf)
- return 0
-
- public Object elementAt(int index)
- return null
-
21Inheritance for Combination
- public class Mouse extends Vegetarian implements
Food -
- protected RealAnimal getChild()
-
-
-
- public int getFoodAmount()
-
-
-
22UML Class diagrams
0..
1
23Composition
- Composition ? has-a relationship (strong
ownership) - Inheritance ? is-a relationship
- Inheritance versus composition
- desire to reuse existing implementation
- substitutability (subtype)
- subclass inherits specification and all methods
and variables - composition allows selective reuse
24UML Class diagramsInheritance versus Composition
public int indexOf(Object obj)
System.out.println(Do not use Set.indexOf)
return 0 public Object elementAt(int index)
System.out.println(Do not use Set.elementAt)
return null
25UML Class diagramsInheritance versus Composition
0..1
1
public void addElement(Object obj)
content.addElement(obj) public int size()
return content.size()
26Generics in Java 1.5
- in Java 1.4
- container classes store object of class Object
- storing elements in a container uses subtype
polymorphism - accessing elements in a container requires type
casting -
- Stack s new Stack()
- s.push(new Integer(3))
- Integer n (Integer) s.pop() // cast required
- s.push(abc) // no error
- Integer second (Integer) s.pop() // runtime
error - // (ClassCastException)
27Generics (contd)
- in Java 1.5
- generic classes (similar to templates in C)
- StackltIntegergt s new StackltIntegergt()
- s.push(new Integer(3))
- Integer n s.pop() // no cast required
- s.push(abc) // type error
- // (at compile time)
28Generic in Java 1.5
- Advantages of generics
- Strong static type-checking
- fewer ClassCastExceptions
- fewer casts
- no unchecked warnings
- Improved readability
- Better tool support
- No future deprecation
29Generics - UML class diagram
A class generic in E
ltltbindgtgt E ? MyClass1
An instantiation of the generic class using the
class MyClass1.
MyInstantiationClass
MyGenericClassltE ? MyClass2gt
Two short forms for an instantiation (useful if
generic class is not part of the diagram.
or
MyGenericClassltMyClass2gt
30Generics - Example
- public class PairltX,Ygt
-
- private X first // first component of type X
- private Y second // second component of type Y
-
- public ltA extends X,B extends Ygt Pair(A a,B b)
- first a
- second b
- // constructor
-
- public Pair(Pairlt? extends X, ? extends Ygt p)
- first p.getFirst()
- second p.getSecond()
- // constructor
31Generics Example (contd)
- public X getFirst()
- return first
- // getFirst
-
- public void setFirst(X x)
- first x
- // setFirst
public Y getSecond() return second //
getSecond public void setSecond(Y y) second
y // setSecond
public boolean equals(Object obj) if (obj
instanceof Pairlt?,?gt) Pairlt?,?gt p
(Pairlt?,?gt) obj return first p.getFirst()
second p.getSecond() return false
// equals
32Auto boxing
- in Java 1.4
- Stack s new Stack()
- s.push(new Integer(3)) // wrapper class needed
- Integer n (Integer) s.pop()
- in Java 1.5
- StackltIntegergt s new StackltIntegergt()
- s.push(3) // auto boxing
- int n s.pop() // again auto boxing
- s.push(new Integer(1)) // without boxing
- Integer num s.pop() // again without boxing
- s.push(2) // any combination
- num s.pop() // possible
33Iterations
- in Java 1.4
- List strings
- ...
- for(int i 0 i lt strings.size() i)
- String str strings.elementAt(i)
- System.out.println(str)
-
- or better using an iterator
- for(Iterator iter strings.iterator()
iter.hasNext()) - String str (String) iter.next()
- System.out.println(str)
-
34Iterations (contd)
- in Java 1.5
- ListltStringgt strings
- ...
- for(String str strings) System.out.println(str)
- int vector new int100
- ...
- int sum 0
- for(int elem vector) sum elem
35Enumeration types in Java 1.5
- in Java 1.4
- enumeration types are implemented by using the
type int - public static final int RED 0
- public static final int YELLOW 1
- public static final int BLUE 2
- ...
- switch(myColor)
- case Color.RED System.out.println(red)
break - case Color.YELLOW System.out.println(yellow)
break - case Color.BLUE System.out.println(blue)
break
36Enumeration types (contd)
- Advantages of explicit enumeration types
- they are type safe (checked at compile time)
- int enums don't provide any type safety at all
- they provide a proper name space for the
enumerated type - with int enums you have to prefix the constants
to get any semblance of a name space - they are robust
- int enums are compiled into clients, and you have
to recompile clients if you add, remove, or
reorder constants - printed values are informative
- if you print an int enum you just see a number
- can be stored in collections (objects)
- arbitrary fields and methods can be added
37Enumeration types (contd)
- Simple example
- public enum Color RED, YELLOW, BLUE
- ...
- for (Color myColor Color.values())
System.out.println(myColor) - values() is a static method of an enumeration
type returning an array - containing all the values of the enum type in the
order they are declared.
38- public enum Planet
- MERCURY (3.303e23, 2.4397e6),
- VENUS (4.869e24, 6.0518e6),
- EARTH (5.976e24, 6.37814e6),
- MARS (6.421e23, 3.3972e6),
- JUPITER (1.9e27, 7.1492e7),
- SATURN (5.688e26, 6.0268e7),
- URANUS (8.686e25, 2.5559e7),
- NEPTUNE (1.024e26, 2.4746e7),
- PLUTO (1.27e22, 1.137e6)
-
- private final double mass // in kilograms
- private final double radius // in meters
- Planet(double mass, double radius)
- this.mass mass
- this.radius radius
-
-
39- public enum Operation
- PLUS double eval(double x, double y) return
x y , - MINUS double eval(double x, double y) return
x - y , - TIMES double eval(double x, double y) return
x y , - DIVIDE double eval(double x, double y)
return x / y - // Do arithmetic op represented by this constant
abstract double eval(double x, double y) -
- public static void main(String args)
- double x Double.parseDouble(args0)
- double y Double.parseDouble(args1)
- for (Operation op Operation.values())
System.out.printf("fsffn",x,op,y,op.eval(x,
y)) -
40Enum types - UML class diagram
41Static import
- Static import
- in Java 1.4
- double sinus Math.sin(Math.PI/2.0)
- in Java 1.5
- import static java.lang.Math.
- double sinus sin(PI/2.0)
- import of all static components of a class
- usage without class prefix
- different from
- import java.util.