Lecture 03 
Software Design 1
Agenda 
 Programming with Objects 
– Classes 
– Interfaces 
– Generic programming 
– Reflection 
 Software Design 
– Ducks…
Reading 
 Barbin Introduction, 1 Core Principles 
– Separation of concerns (SoC) 
– Coupling 
– Cohesion 
– Information Hiding 
 Don’t Repeat Yourself 
 Polymorphism 
 Optional: 
– http://docs.oracle.com/javase/tutorial/
Programming with Objects
Object Oriented Programming 
 Object Oriented programming can be powerful 
– One of the best ways for general purpose computing 
 But 
– The power of object oriented languages needs to be 
used properly! 
 However 
– Programmers tend to forget the power of OO
Object Oriented Programming
Object Oriented Programming 
 Programming languages with objects 
– Objects hold data and methods 
– Object variables (reference) point to objects 
 Object Oriented 
– Object are instances of classes, created with new 
– Classes describe the objects 
– Classes extend other classes – inheritance 
– Instance variables are encapsulated 
– Methods manipulate instance variable
EXERCISE 
Explain these concepts and why they are important in programming 
Encapsulation 
Interfaces 
Polymorphism
Think About This! 
 Object-oriented programming 
– Is not about class inheritance and creating advanced 
class diagrams 
 Remember 
– Encapsulation – Hiding data 
– Interfaces – Hiding implementation 
– Polymorphism – Flexible and Generic Programming 
 Powerful programming 
– Separation of concerns 
– Separating what varies from what stays the same
Think About This! 
 Object-oriented programming 
– Is not about class inheritance and creating advanced 
class diagrams 
 Remember 
– Encapsulation – Hiding data 
– Interfaces – Hiding implementation 
– Polymorphism – Flexible and Generic Programming 
 Powerful programming 
– Separation of concerns 
– Separating what varies from what stays the same
Separate Variations Design Principle 
Identify the aspects of 
your application that 
vary and separate 
them from what stays the 
same
Don’t Repeat Yourself – DRY 
 Single source of truth 
Every piece of knowledge 
must have a single, 
unambiguous, authoritative 
representation within a 
system
Object Oriented Design 
 Design of classes and interfaces 
– Class diagram shows relationships 
– Sequence diagrams show flows 
 Design Patterns 
– Reoccurring solutions in design 
– “Best practices” – known solutions for common 
problems
Classes
Objects 
 Object created 
Date day1; 
Date day2 = new Date(); 
System.out.println (new Date ()); 
String s = new Date().toString (); 
 Object used 
day1 null 
day2 
Date 
Date now = new Date(); 
if (day2.before(now)) 
{ 
System.out.println (day2.toString()); 
} 
before 
tostring 
...
Objects 
 Operator new creates 
memory 
– String is an exception 
 Reference variables 
always point to some memory 
day1 null 
day2 
Date 
before 
tostring 
... 
Date d = new Date(); 
Must be a concrete 
class 
Can be any supertype or 
interface of the concrete class
Classes 
Object 
User 
-id : int 
-name : String 
-username : String 
-password : String 
-email : String 
+getId() : String 
 Classes extend other classes 
– Concrete Inheritance 
– Subtype extends supertype 
 Class contains 
– Instance variables 
– Methods 
 Reference variables of type 
Object points to any class 
– Any supertype can reference subtype 
Object obj = new User (); 
User u = (User)obj; 
supertype 
subtype
Class methods 
 Methods can be overridden 
– Class extends a class and overrides a method 
 Methods can be overloaded 
– Same method with different parameters 
 Methods can be 
– public – any class can call the method 
– private – only available within the class 
– protected – only available within the class and 
extended classes
QUIZ 
Class A inherits class B. A overwrites method f. Variable b is created like 
this: 
B b = new A(); 
What happens when this line is run: 
b.f(); 
A) The method in A is run 
B) The method in B is run 
C) First the method in B is run, then the method in A 
D) The new statement is illegal and does not compile
QUIZ 
Class A inherits class B. A overwrites method f. Variable b is created like 
this: 
B b = new A(); 
What happens when this line is run: 
b.f(); 
A) The method in A is run 
B) The method in B is run 
C) First the method in B is run, then the method in A 
D) The new statement is illegal and does not compile 
✔
Classes 
 References 
– Point to concrete objects 
– Must be same type or supertype of concrete object 
– Can be interface or abstract class 
Object obj = new Date (); 
Date d = (Date)obj;
Constructors 
 Classes have constructor 
– Instantiation methods 
– Same name as the class 
 References 
– this – refers to the class 
– super – extended class 
public Employee (String name, 
double salary) 
{ 
this (name); 
this.salary = salary; 
} 
public Manager (String name) 
{ 
super (name, 0.0); 
... 
}
class Point 
{ 
private int x, y; 
public Point () 
{ 
x = 0; y = 0; 
} 
public Point (int x, int y) 
{ 
this.x = x; this.y = y; 
} 
public void move (intdx, intdy) 
{ 
x+=dx;y+=dy; 
} 
public String toString () 
{ 
return "(" + x + "," + y + ")"; 
} 
} 
Class variables 
Default constructors 
Overloaded constructor 
this used to refer to the 
class variables 
Override toString 
method of Object 
Example
Example 
Bla 
public class Test 
{ 
public static void main (String[] args) 
{ 
System.out.println ("Test"); 
Test test = new Test(); 
} 
public Test () 
{ 
Point p0; // null reference 
Point p1 = new Point (); 
Point p2 = new Point (1,2); 
Object obj = p2; 
p0 = (Point)obj; 
p0.move (1, 1); 
System.out.println("p0=" + p0); 
} 
} 
X = 2 
Y = 3 
C:java>javac Test.java 
C:java>java Test 
Test 
p0=(2,3)
QUIZ 
Java uses this method to pass objects reference to methods 
A) Call by reference 
B) Call by value 
C) Call by method reference 
D) Call by value reference
QUIZ 
Java uses this method to pass objects reference to methods 
A) Call by reference 
B) Call by value 
C) Call by method reference 
D) Call by value reference 
✔
Call By Value 
 Methods use call by value 
– Object references are passed by value 
– The reference cannot change, but the object can 
Point p = new Point (42,0); 
changeReferance(p); 
System.out.println(p.x); 
Point 
x: 
y: 
42 
0 
void changeReferance(Point p) 
{ 
while (p.x>0) p.x--; 
} 
p 
Reference p to Point 
p 
Local copy of a reference 
p to Point 
p is same as this.p
Inheritance 
 Classes extend other classes 
– Subclasses extend superclasses 
class Manager extends Employee 
{ ... } 
 Reference variables of super types can 
reference objects of subtypes 
Employee 
Manager 
Empolyee e; 
e = new Employee(. . .) 
e = new Manager(. . .) 
Polymorphism
public class Employee 
{ 
private String name; 
private double salary; 
private Date hireDate; 
public Employee() 
{ 
} 
public Employee(String name, double salary, Date hireDate) 
{ 
this.name = name; 
this.salary = salary; 
this.hireDate = hireDate; 
} 
public Employee(String name) 
{ 
this.name = name; 
}
public String getName() 
{ 
return name; 
} 
public double getSalary() 
{ 
return salary; 
} 
public void setName(String name) 
{ 
this.name = name; 
} 
public String toString() 
{ 
return "Employee: " + getName(); 
} 
}
class Manager extends Employee 
{ 
String title; 
double bonus; 
public Manager (String name, String title) 
{ 
Bla 
super (name); 
this.title = title; 
} 
public String getTitle () 
{ 
return title; 
} 
public double getSalary() 
{ 
return this.bonus + super.getSalery(); 
} 
public String toString () 
{ 
return "Manager: " + getName() + 
", " + getTitle (); 
} 
} 
New variables 
New method 
Overridden 
methods
What does this program print? 
public class Test2 
{ 
public static void main (String[] args) 
{ 
System.out.println ("Test2"); 
Test2 test2 = new Test2(); 
} 
public Test2 () 
{ 
Employee e0 = new Employee ("Dilbert"); 
Employee e1 = new Manager ("Pointy Haired", "Boss"); 
System.out.println("e0: " + e0); 
System.out.println("e1: " + e1); 
} 
} 
C:java>java Test2 
Test2 
e0: Employee: Dilbert 
e1: Manager: Pointy Haired, Boss 
EXERCISE
Dynamic binding 
 Decision on which method to run is taken at 
runtime 
– The virtual machine uses a method table for each 
class 
Manager m = new Manager(); 
m.setName(“P.H. Carl”); // Employee.setName 
m.setTitle (“Boss”); // Manager.setTitle 
m.getSalary (); // Manager.getSalary 
Employee e1 = new Manager("Pointy Haired", "Boss"); 
e1.getSalary(); 
Is this manager salary 
with bonus?
EXERCISE 
What does this program print? 
public class Test1 
{ 
public static void main(String[] args) 
{ 
System.out.println("Test1"); 
new Test1(); 
} 
public Test1() 
{ 
Employee e0 = new Employee ("Dilbert"); 
Employee e1 = new Manager ("Pointy", "Boss"); 
System.out.println(e1.getTitle(); 
} 
} Trick question! 
Does not compile since getTitle is not in Employee
class Manager extends Employee 
{ 
... 
public double getSalary() 
{ 
return this.bonus + super.getSalery(); 
} 
WHAT IS POSSIBLE WRONG WITH THIS? 
Manager m = new Manager("Fay", "Boss"); 
m.setBonus(200); 
// meantime, somewhere else 
Employee e = (Employee)something.getEmployees(); 
m.setSalary(100); 
System.out.println(e.getSalary()); // should print 100 
Violates the Liskov substitution principle
Think About This! 
 Why use Concrete Inheritance? 
– Powerful implementation approach 
– Layered Supertype Pattern 
– Enables polymorphism if supertypes are used 
– New classes can be added without recompile 
 But remember 
– Object oriented programming is not just about 
concrete inheritance 
– It has to be natural! 
– Class hierarchies are rigid 
– Not always good to force others to extend
Abstract Classes 
 Abstract classes put the responsibility of 
implementation on subclasses 
– Classes extending an abstract class must implement 
the abstract methods 
– Can contain both concrete and abstract methods 
– Normal classes are concrete classes 
 Abstract classes cannot be instantiated 
 Reference variables of abstract types are 
allowed 
– Object must be a concrete class
Abstract Example 
abstract class Person 
{ 
private String name; 
public Person(String name) 
{ 
this.name = name; 
} 
// get and set methods ... 
public abstract String getDescription (); 
} 
class Employee extends Person 
{ 
public String getDescription() 
{ 
return "Employee called " + super.getName(); 
} 
} 
// Person p1 = new Person (); Does not work! 
Person p2; 
Person p3 = new Employee ("Dilbert"); 
System.out.println (p3.getDescription()); 
Key Concept: Polymorphism
Interfaces
Interfaces 
 Interface is a class without implementation 
– Declaration of how to implement class 
– All methods and variables are static final 
 Classes implement interfaces 
– implements keyword 
– Must implement all the methods – or be abstract
Interfaces 
public interface Comparable 
{ 
public int compareTo(Object other); 
} 
class Employee extends Person implements Comparable 
{ 
public int compareTo(Object o) 
{ ...
Example 
public interface Comparable 
{ 
public int compareTo(Object other); 
} 
class Employee extends Person implements Comparable 
{ 
public int compareTo(Object o) 
{ 
Employee e = (Employee)o; 
return this.getName().compareTo (e.getName()); 
} ... 
Employee[] ale = new Employee[3]; 
ale[0] = new Employee ("Dilbert"); 
ale[1] = new Employee ("Wally"); 
ale[2] = new Employee ("Alice"); 
Arrays.sort(ale); 
for (int j=0; j <ale.length; j++) 
System.out.println(ale[j].getName()); 
How is this 
possible? 
Alice 
Dilbert 
Wally
Think About This! 
 Class A calls class B -> A depends on B 
 Class java.util.Arrays calls the 
Employee.compareTo method 
 Does Arrays depend on Employee? 
Polymorphism 
Separated interface
Many Faces 
 Arrays looks at the class as Comparable, while 
we regard it as Employee 
Class Employee 
implements Comparable 
{ 
... 
compare 
Class Arrays 
... 
sort(Object[] 
{ 
Comparable c ... 
Test... 
Arrays.sort(persons 
Arrays does NOT call Employee.compareTo, 
it calls Comaparable.compareTo 
which happens to be Employee Polymorphism
Objects 
abstract class Person implements Comparable 
class Employee extends Person 
class Manager extends Employee 
Must be 
concrete class 
Object o = new Manager() 
Person p = new Manager() 
Comparable c = new Manager() 
Employee e = new Manager() 
Manager m = new Manager() 
Memory for Manager 
reference 
Can be any 
supertype
Using Interfaces 
 Interfaces cannot be instantiated 
– Variables of interface types can reference objects that 
implement the interface 
Comarable c = new Comparable (); // NO!!! 
Comarable c = new Employee (); // OK! 
 Interface can extend interfaces 
public interface Powered extends Movable 
{ 
double milesPerGallon(); 
double SPEED_LIMIT = 95; 
}
Why interfaces? 
 Why not use abstract classes? 
– Only one class can be extended 
– Class hierarchies are rigid and not always suitable 
 Interfaces can improve software design 
– Provide abstraction – hide the implementation 
– Classes that use interfaces are not dependant on a 
particular implementation 
class Employee extends Person implements Comparable 
{ 
...
Example Pattern 
 Table Data Gateway or Data Access Object 
provide an interface to database table 
– Decision on what database access methods to use 
can be configured 
 Example 
public interface TeamDAO extends RuDAO 
{ 
public void addTeam (Team team); 
public Collection getTeams (); 
} 
Interface 
Implementation 
Client 
code
Example: Drawing system 
public interface Drawable 
{ 
public void draw (); 
} 
public class Rectangle extends Shape 
{ 
private int h, w; 
public Rectangle (int x, int y, int h, int w) 
{ 
this.x=x; this.y=y; this.h=h; this.w=w; 
} 
public void draw () 
{ 
System.out.println ("Rectange (x="+x+",y="+y+",h="+h+",w="+w+")"); 
} 
} 
public abstract class Shape implements Drawable 
{ 
protected int x,y; 
} 
public class Circle extends Shape 
{ 
private int r; 
public Circle(int x, int y, int r) 
{ 
this.x = x; this.y = y; this.r = r; 
} 
public void draw() 
{ 
System.out.println ("Circle (x="+x+",y="+y+",r="+r+")"); 
} 
}
Example: Drawing system 
 Drawing all objects 
– All draw objects implement Drawable 
public DrawTest() 
{ 
List<Drawable> l = new ArrayList<Drawable>(); 
l.add(new Rectangle(1, 1, 1, 1)); 
l.add(new Circle(2, 1, 1)); 
l.add(new Rectangle(8, 4, 1, 1)); 
for (Drawable d: l) 
{ 
d.draw(); 
} 
} 
Rectange (x=1,y=1,h=1,w=1) 
Circle (x=2,y=1,r=1) 
Rectange (x=8,y=4,h=1,w=1)
Think About This! 
 All drawing objects in this Layer extend Shape 
Shape is Layered Supertype 
 Shape is abstract and implements Drawable 
Shape is Template Method 
 Client code does not know about the classes 
that implement Drawable 
Generic Programming
QUIZ 
X extends Y. Which is true? 
A) Correct if and only if X is a class and Y is an interface 
B) Correct if and only if X is an interface and Y is a class 
C) Correct if X and Y are either both classes or both interfaces 
D) Correct for all combinations of X and Y being classes and/or interfaces.
QUIZ 
X extends Y. Which is true? 
A) Correct if and only if X is a class and Y is an interface 
B) Correct if and only if X is an interface and Y is a class 
C) Correct if X and Y are either both classes or both interfaces 
D) Correct for all combinations of X and Y being classes and/or interfaces. 
✔

L03 Software Design

  • 1.
  • 2.
    Agenda  Programmingwith Objects – Classes – Interfaces – Generic programming – Reflection  Software Design – Ducks…
  • 3.
    Reading  BarbinIntroduction, 1 Core Principles – Separation of concerns (SoC) – Coupling – Cohesion – Information Hiding  Don’t Repeat Yourself  Polymorphism  Optional: – http://docs.oracle.com/javase/tutorial/
  • 4.
  • 5.
    Object Oriented Programming  Object Oriented programming can be powerful – One of the best ways for general purpose computing  But – The power of object oriented languages needs to be used properly!  However – Programmers tend to forget the power of OO
  • 6.
  • 7.
    Object Oriented Programming  Programming languages with objects – Objects hold data and methods – Object variables (reference) point to objects  Object Oriented – Object are instances of classes, created with new – Classes describe the objects – Classes extend other classes – inheritance – Instance variables are encapsulated – Methods manipulate instance variable
  • 8.
    EXERCISE Explain theseconcepts and why they are important in programming Encapsulation Interfaces Polymorphism
  • 9.
    Think About This!  Object-oriented programming – Is not about class inheritance and creating advanced class diagrams  Remember – Encapsulation – Hiding data – Interfaces – Hiding implementation – Polymorphism – Flexible and Generic Programming  Powerful programming – Separation of concerns – Separating what varies from what stays the same
  • 10.
    Think About This!  Object-oriented programming – Is not about class inheritance and creating advanced class diagrams  Remember – Encapsulation – Hiding data – Interfaces – Hiding implementation – Polymorphism – Flexible and Generic Programming  Powerful programming – Separation of concerns – Separating what varies from what stays the same
  • 11.
    Separate Variations DesignPrinciple Identify the aspects of your application that vary and separate them from what stays the same
  • 12.
    Don’t Repeat Yourself– DRY  Single source of truth Every piece of knowledge must have a single, unambiguous, authoritative representation within a system
  • 13.
    Object Oriented Design  Design of classes and interfaces – Class diagram shows relationships – Sequence diagrams show flows  Design Patterns – Reoccurring solutions in design – “Best practices” – known solutions for common problems
  • 14.
  • 15.
    Objects  Objectcreated Date day1; Date day2 = new Date(); System.out.println (new Date ()); String s = new Date().toString ();  Object used day1 null day2 Date Date now = new Date(); if (day2.before(now)) { System.out.println (day2.toString()); } before tostring ...
  • 16.
    Objects  Operatornew creates memory – String is an exception  Reference variables always point to some memory day1 null day2 Date before tostring ... Date d = new Date(); Must be a concrete class Can be any supertype or interface of the concrete class
  • 17.
    Classes Object User -id : int -name : String -username : String -password : String -email : String +getId() : String  Classes extend other classes – Concrete Inheritance – Subtype extends supertype  Class contains – Instance variables – Methods  Reference variables of type Object points to any class – Any supertype can reference subtype Object obj = new User (); User u = (User)obj; supertype subtype
  • 18.
    Class methods Methods can be overridden – Class extends a class and overrides a method  Methods can be overloaded – Same method with different parameters  Methods can be – public – any class can call the method – private – only available within the class – protected – only available within the class and extended classes
  • 19.
    QUIZ Class Ainherits class B. A overwrites method f. Variable b is created like this: B b = new A(); What happens when this line is run: b.f(); A) The method in A is run B) The method in B is run C) First the method in B is run, then the method in A D) The new statement is illegal and does not compile
  • 20.
    QUIZ Class Ainherits class B. A overwrites method f. Variable b is created like this: B b = new A(); What happens when this line is run: b.f(); A) The method in A is run B) The method in B is run C) First the method in B is run, then the method in A D) The new statement is illegal and does not compile ✔
  • 21.
    Classes  References – Point to concrete objects – Must be same type or supertype of concrete object – Can be interface or abstract class Object obj = new Date (); Date d = (Date)obj;
  • 22.
    Constructors  Classeshave constructor – Instantiation methods – Same name as the class  References – this – refers to the class – super – extended class public Employee (String name, double salary) { this (name); this.salary = salary; } public Manager (String name) { super (name, 0.0); ... }
  • 23.
    class Point { private int x, y; public Point () { x = 0; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; } public void move (intdx, intdy) { x+=dx;y+=dy; } public String toString () { return "(" + x + "," + y + ")"; } } Class variables Default constructors Overloaded constructor this used to refer to the class variables Override toString method of Object Example
  • 24.
    Example Bla publicclass Test { public static void main (String[] args) { System.out.println ("Test"); Test test = new Test(); } public Test () { Point p0; // null reference Point p1 = new Point (); Point p2 = new Point (1,2); Object obj = p2; p0 = (Point)obj; p0.move (1, 1); System.out.println("p0=" + p0); } } X = 2 Y = 3 C:java>javac Test.java C:java>java Test Test p0=(2,3)
  • 25.
    QUIZ Java usesthis method to pass objects reference to methods A) Call by reference B) Call by value C) Call by method reference D) Call by value reference
  • 26.
    QUIZ Java usesthis method to pass objects reference to methods A) Call by reference B) Call by value C) Call by method reference D) Call by value reference ✔
  • 27.
    Call By Value  Methods use call by value – Object references are passed by value – The reference cannot change, but the object can Point p = new Point (42,0); changeReferance(p); System.out.println(p.x); Point x: y: 42 0 void changeReferance(Point p) { while (p.x>0) p.x--; } p Reference p to Point p Local copy of a reference p to Point p is same as this.p
  • 28.
    Inheritance  Classesextend other classes – Subclasses extend superclasses class Manager extends Employee { ... }  Reference variables of super types can reference objects of subtypes Employee Manager Empolyee e; e = new Employee(. . .) e = new Manager(. . .) Polymorphism
  • 29.
    public class Employee { private String name; private double salary; private Date hireDate; public Employee() { } public Employee(String name, double salary, Date hireDate) { this.name = name; this.salary = salary; this.hireDate = hireDate; } public Employee(String name) { this.name = name; }
  • 30.
    public String getName() { return name; } public double getSalary() { return salary; } public void setName(String name) { this.name = name; } public String toString() { return "Employee: " + getName(); } }
  • 31.
    class Manager extendsEmployee { String title; double bonus; public Manager (String name, String title) { Bla super (name); this.title = title; } public String getTitle () { return title; } public double getSalary() { return this.bonus + super.getSalery(); } public String toString () { return "Manager: " + getName() + ", " + getTitle (); } } New variables New method Overridden methods
  • 32.
    What does thisprogram print? public class Test2 { public static void main (String[] args) { System.out.println ("Test2"); Test2 test2 = new Test2(); } public Test2 () { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy Haired", "Boss"); System.out.println("e0: " + e0); System.out.println("e1: " + e1); } } C:java>java Test2 Test2 e0: Employee: Dilbert e1: Manager: Pointy Haired, Boss EXERCISE
  • 33.
    Dynamic binding Decision on which method to run is taken at runtime – The virtual machine uses a method table for each class Manager m = new Manager(); m.setName(“P.H. Carl”); // Employee.setName m.setTitle (“Boss”); // Manager.setTitle m.getSalary (); // Manager.getSalary Employee e1 = new Manager("Pointy Haired", "Boss"); e1.getSalary(); Is this manager salary with bonus?
  • 34.
    EXERCISE What doesthis program print? public class Test1 { public static void main(String[] args) { System.out.println("Test1"); new Test1(); } public Test1() { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy", "Boss"); System.out.println(e1.getTitle(); } } Trick question! Does not compile since getTitle is not in Employee
  • 35.
    class Manager extendsEmployee { ... public double getSalary() { return this.bonus + super.getSalery(); } WHAT IS POSSIBLE WRONG WITH THIS? Manager m = new Manager("Fay", "Boss"); m.setBonus(200); // meantime, somewhere else Employee e = (Employee)something.getEmployees(); m.setSalary(100); System.out.println(e.getSalary()); // should print 100 Violates the Liskov substitution principle
  • 36.
    Think About This!  Why use Concrete Inheritance? – Powerful implementation approach – Layered Supertype Pattern – Enables polymorphism if supertypes are used – New classes can be added without recompile  But remember – Object oriented programming is not just about concrete inheritance – It has to be natural! – Class hierarchies are rigid – Not always good to force others to extend
  • 37.
    Abstract Classes Abstract classes put the responsibility of implementation on subclasses – Classes extending an abstract class must implement the abstract methods – Can contain both concrete and abstract methods – Normal classes are concrete classes  Abstract classes cannot be instantiated  Reference variables of abstract types are allowed – Object must be a concrete class
  • 38.
    Abstract Example abstractclass Person { private String name; public Person(String name) { this.name = name; } // get and set methods ... public abstract String getDescription (); } class Employee extends Person { public String getDescription() { return "Employee called " + super.getName(); } } // Person p1 = new Person (); Does not work! Person p2; Person p3 = new Employee ("Dilbert"); System.out.println (p3.getDescription()); Key Concept: Polymorphism
  • 39.
  • 40.
    Interfaces  Interfaceis a class without implementation – Declaration of how to implement class – All methods and variables are static final  Classes implement interfaces – implements keyword – Must implement all the methods – or be abstract
  • 41.
    Interfaces public interfaceComparable { public int compareTo(Object other); } class Employee extends Person implements Comparable { public int compareTo(Object o) { ...
  • 42.
    Example public interfaceComparable { public int compareTo(Object other); } class Employee extends Person implements Comparable { public int compareTo(Object o) { Employee e = (Employee)o; return this.getName().compareTo (e.getName()); } ... Employee[] ale = new Employee[3]; ale[0] = new Employee ("Dilbert"); ale[1] = new Employee ("Wally"); ale[2] = new Employee ("Alice"); Arrays.sort(ale); for (int j=0; j <ale.length; j++) System.out.println(ale[j].getName()); How is this possible? Alice Dilbert Wally
  • 43.
    Think About This!  Class A calls class B -> A depends on B  Class java.util.Arrays calls the Employee.compareTo method  Does Arrays depend on Employee? Polymorphism Separated interface
  • 44.
    Many Faces Arrays looks at the class as Comparable, while we regard it as Employee Class Employee implements Comparable { ... compare Class Arrays ... sort(Object[] { Comparable c ... Test... Arrays.sort(persons Arrays does NOT call Employee.compareTo, it calls Comaparable.compareTo which happens to be Employee Polymorphism
  • 45.
    Objects abstract classPerson implements Comparable class Employee extends Person class Manager extends Employee Must be concrete class Object o = new Manager() Person p = new Manager() Comparable c = new Manager() Employee e = new Manager() Manager m = new Manager() Memory for Manager reference Can be any supertype
  • 46.
    Using Interfaces Interfaces cannot be instantiated – Variables of interface types can reference objects that implement the interface Comarable c = new Comparable (); // NO!!! Comarable c = new Employee (); // OK!  Interface can extend interfaces public interface Powered extends Movable { double milesPerGallon(); double SPEED_LIMIT = 95; }
  • 47.
    Why interfaces? Why not use abstract classes? – Only one class can be extended – Class hierarchies are rigid and not always suitable  Interfaces can improve software design – Provide abstraction – hide the implementation – Classes that use interfaces are not dependant on a particular implementation class Employee extends Person implements Comparable { ...
  • 48.
    Example Pattern Table Data Gateway or Data Access Object provide an interface to database table – Decision on what database access methods to use can be configured  Example public interface TeamDAO extends RuDAO { public void addTeam (Team team); public Collection getTeams (); } Interface Implementation Client code
  • 49.
    Example: Drawing system public interface Drawable { public void draw (); } public class Rectangle extends Shape { private int h, w; public Rectangle (int x, int y, int h, int w) { this.x=x; this.y=y; this.h=h; this.w=w; } public void draw () { System.out.println ("Rectange (x="+x+",y="+y+",h="+h+",w="+w+")"); } } public abstract class Shape implements Drawable { protected int x,y; } public class Circle extends Shape { private int r; public Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } public void draw() { System.out.println ("Circle (x="+x+",y="+y+",r="+r+")"); } }
  • 50.
    Example: Drawing system  Drawing all objects – All draw objects implement Drawable public DrawTest() { List<Drawable> l = new ArrayList<Drawable>(); l.add(new Rectangle(1, 1, 1, 1)); l.add(new Circle(2, 1, 1)); l.add(new Rectangle(8, 4, 1, 1)); for (Drawable d: l) { d.draw(); } } Rectange (x=1,y=1,h=1,w=1) Circle (x=2,y=1,r=1) Rectange (x=8,y=4,h=1,w=1)
  • 51.
    Think About This!  All drawing objects in this Layer extend Shape Shape is Layered Supertype  Shape is abstract and implements Drawable Shape is Template Method  Client code does not know about the classes that implement Drawable Generic Programming
  • 52.
    QUIZ X extendsY. Which is true? A) Correct if and only if X is a class and Y is an interface B) Correct if and only if X is an interface and Y is a class C) Correct if X and Y are either both classes or both interfaces D) Correct for all combinations of X and Y being classes and/or interfaces.
  • 53.
    QUIZ X extendsY. Which is true? A) Correct if and only if X is a class and Y is an interface B) Correct if and only if X is an interface and Y is a class C) Correct if X and Y are either both classes or both interfaces D) Correct for all combinations of X and Y being classes and/or interfaces. ✔

Editor's Notes

  • #6 OO is one way – not the only way For general purpose computations, OO is really good