Download Document

Document related concepts

Abstraction (computer science) wikipedia , lookup

Name mangling wikipedia , lookup

Java (programming language) wikipedia , lookup

Java performance wikipedia , lookup

Class (computer programming) wikipedia , lookup

Design Patterns wikipedia , lookup

C Sharp syntax wikipedia , lookup

C++ wikipedia , lookup

Object-oriented programming wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Transcript
Introduction (3)
Chapter 1 (3)
Object-Oriented Modeling and Design
Byung-Hyun Ha
[email protected]
Lecture Outline
 Introduction (rev.)
 Polymorphism
 Polymorphism examples
 Object-oriented development
 Object-oriented methodology
 Tree models of OMT
 Object-oriented themes
Introduction (rev.)
 Required characteristics for OO
 Identity
 Classification
 Polymorphism
• The same operation may behave differently on different classes
 Inheritance
Polymorphism
 Same operation behaves differently?
 e.g. speak() behavior of animals
• Cat, dog, and pig are all animals and they can speak.
• But, dog: woof-woof, cat: meow, pig: oink-oink
 Example program
 Assume a set of animals that can speak
 # of animals of each type is specified by a user
• i.e. a user inputs # of dogs, # of cats, and # of pigs.
 Then, animals will speak
First Program
 Outline
import java.util.*;
public class Farm {
static int[] a_set;
public static void main(String[] args) {
input();
speak();
}
static void input() {
...
}
static void speak() {
...
}
}
First Program
public class Farm {
...
private static void input() {
Scanner s = new Scanner(System.in);
int dogs = s.nextInt();
int cats = s.nextInt();
int pigs = s.nextInt();
a_set = new int[dogs + cats + pigs];
for (int i = 0; i < dogs;
a_set[i] = 0;
}
for (int i = 0; i < cats;
a_set[dogs + i] = 1;
}
for (int i = 0; i < pigs;
a_set[dogs + cats + i]
}
}
}
i++) {
// 0 means dog
i++) {
// 1 means cat
i++) {
= 2;
// 2 means pig
First Program
 We call it as ‘procedural way’
public class Farm {
...
static void speak() {
for (int i = 0; i < a_set.length; i++) {
if (a_set[i] == 0) {
System.out.println("woof-woof");
} else if (a_set[i] == 1) {
System.out.println("meow");
} else if (a_set[i] == 2) {
System.out.println("oink-oink");
}
}
}
}
First Program
 Works well?
 If we want to handle another animal (e.g. hen),
 which part do we need to rewrite?
 If dog’s crying sound depends on its health,
 how can we handle?
 If we want to add ‘move’ behavior,
 will it be easy?
 Anyway, what does it mean by 0, 1, and 2?
 We specify the meaning using comments
• Actually comments are not formal code (machine doesn’t know!)
 Probably, others may be confused and can misuse!
Polymorphism
 For those situation, polymorphism will be helpful.
 Before move further, recall inheritance example
public class A {
public class B extends A {
int f1 = 3;
int f2 = 5;
void m1() {
System.out.println(f1);
}
void m1() {
f1 = f1 + f2;
super.m1();
}
}
public static void
main(String[] args) {
A x = new B();
x.m1();
}
}
Polymorphism
 OO approach (somewhat complex…)
 First, we define class Animal
• “Animals can speak.”
• A kind of classification work
 Next, we refine each specific animal from the general animal
• “A dog is an animal, a cat is an animal, and a pig is an animal.”
• “A dog barks, a cat mews, and a pig oinks.”
• A kind of inheritance work
Animal
Dog
Cat
Pig
Better Program
 Animal and related classes
public class Animal {
void speak() {
System.out.println("...");
}
}
public class Dog extends Animal {
void speak() {
System.out.println("woof-woof");
}
}
public class Cat extends Animal {
void speak() {
System.out.println("meow");
}
}
public class Pig extends Animal {
void speak() {
System.out.println("oink-oink");
}
}
Better Program
 Outline
import java.util.*;
public class Farm {
static Animal[] a_set;
public static void main(String[] args) {
input();
speak();
}
static void input() {
...
}
static void speak() {
...
}
}
Better Program
public class Farm {
...
private static void input() {
Scanner s = new Scanner(System.in);
int dogs = s.nextInt();
int cats = s.nextInt();
int pigs = s.nextInt();
a_set = new Animal[dogs + cats + pigs];
for (int i = 0; i < dogs; i++) {
a_set[i] = new Dog();
}
for (int i = 0; i < cats; i++) {
a_set[dogs + i] = new Cat();
}
for (int i = 0; i < pigs; i++) {
a_set[dogs + cats + i] = new Pig();
}
}
}
Better Program
 Just speak!
public class Farm {
static Animal[] a_set;
...
static void speak() {
for (int i = 0; i < a_set.length; i++) {
a_set[i].speak();
}
}
}
Think Again
 If we want to handle another animal (e.g. hen),
 which part do we need to rewrite?
 If dog’s crying sound depends on its health,
 how can we handle?
 If we want to add ‘move’ behavior,
 will it be easy?
 Anyway, program is clear to understand.
OO Characteristics (rev.)
 Polymorphism
 The same operation may behave differently on different classes
 When to use concept of polymorphism
 Handling a collection of similar objects with different behavior
• e.g. PowerPoint
 Supporting the feature which will be specified in future
• e.g. toString() method, priority queue
 Coping with extension (or reuse)
• e.g. Window programming in Java (Swing)
 We cannot help using polymorphism, if we really
write OO program!
toString() method
 Display current date and time
public class A {
public static void main(String[] args) {
java.util.Date date = new java.util.Date();
System.out.println(date);
}
}
Mon Mar 17 21:23:16 KST 2008
toString() method
 Then, how about our Vector? Why isn’t it pretty?
public class Vector {
double x;
double y;
}
public class A {
public static void main(String[] args) {
Vector a = new Vector();
a.x = 1.0; a.y = 2.0;
System.out.println(a);
}
}
Vector@de6ced
toString() method
 The problem is that Java don’t know how to display
Vector object
 But we know it!
 Suppose we want our Vector to be displayed as
follows:
(1.0,2.0)
 Then, we should inform Java of it!
 But how?
toString() method
 Add toString() method to class Vector as follows, and
run again.
public class Vector {
double x;
double y;
public String toString() {
return "(" + x + "," + y + ")";
}
}
(1.0,2.0)
toString() method
 The secret
 All classes in Java inherits class Object implicitly.
 That is, Java assume you just omitted ‘extends Object’.
public class Vector extends Object {
double x;
double y;
public String toString() {
return "(" + x + "," + y + ")";
}
}
toString() method
 Class Object has the following method:
 String toString()
 And, System.out.println(Object x) displays x.toString()
on screen
 Recall that polymorphism is “the same operation may behave
differently on different classes”
Object
toString()
Date
toString()
Vector
toString()
Priority Queue
 Data structure with operations
 Add an element to the queue with an associated priority
 Return the element from the queue that has the highest priority
 Like these,
 add 3, add 5, add 1, add 3, add 4
 return? 1, return? 3, return? 3, return? 4, return? 5
 Very frequently used for implementing various
algorithms
 because of the time complexity with O(log n)
Priority Queue
 With Java
import java.util.*;
public class PQ {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
q.add(3);
q.add(5);
q.add(1);
q.add(3);
q.add(4);
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
}
}
1
3
3
4
5
Priority Queue with Our Class
 Then, how about animal?
 Assume an animal has its age and weight.
 We want to use priority queue for animal objects with regard to
their ages.
public class Animal {
int age;
double weight;
Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public String toString() {
return "Animal: " + age + " " + weight;
}
}
Priority Queue with Our Class
 Is it possible? What is the problem?
import java.util.*;
public class PQ {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
q.add(new Animal(3, 9.2));
q.add(new Animal(5, 12.0));
q.add(new Animal(1, 20.7));
q.add(new Animal(3, 5.2));
q.add(new Animal(4, 8.1));
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
System.out.println(q.poll());
}
}
Priority Queue with Our Class
 Java says,
Exception in thread "main" java.lang.ClassCastException:
Animal cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at PQ.main(PQ.java:8)
Priority Queue with Our Class
 PriorityQueue need know how to make ordering on
animal objects.
 That is, we have to specify which object is greater than the other
between two.
 Recall the method equals()
 Also in this case, the problem is that we know but
PriorityQueue don’t know.
 Then how can we inform PriorityQueue about it?
 Use interface ‘Comparable’
 PriorityQueue was implemented to be operated with interface
‘Comparable’.
 Consult Java API reference for further information.
Priority Queue with Our Class
 Java API reference says that there is method
compareTo() in interface Comparable, and
 int compareTo(T o)
• Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less than,
equal to, or greater than the specified object.
• …
Priority Queue with Our Class
 Revised class Animal
public class Animal implements Comparable {
int age;
double weight;
Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public int compareTo(Object o) {
Animal other = (Animal)o;
return age - other.age;
}
Animal:
Animal:
Animal:
Animal:
Animal:
public String toString() {
return "Animal: " + age + " " + weight;
}
}
1
3
3
4
5
20.7
5.2
9.2
8.1
12.0
Priority Queue with Our Class
 Question
 We want to use priority queue for animal objects with regard to
their weights. How should we rewrite?
public class Animal implements Comparable {
int age;
double weight;
Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public int compareTo(Object o) {
Animal other = (Animal)o;
return age - other.age;
}
public String toString() {
return "Animal: " + age + " " + weight;
Priority Queue with Our Class
public class Animal implements Comparable {
int age;
double weight;
Animal(int age, double weight) {
this.age = age;
this.weight = weight;
}
public int compareTo(Object o) {
Animal other = (Animal)o;
double d = weight - other.weight;
if (d < 0) {
return -1;
} else if (d == 0) {
return 0;
} else {
return 1;
}
}
Animal:
Animal:
Animal:
Animal:
Animal:
3
4
3
5
1
5.2
8.1
9.2
12.0
20.7
Java Window Programming
 Problem of our Calc
 When ‘+’ button is pressed, how can we handle the event?
 Question
 If you were the developer of Swing, how would you design the
framework with which a user can easily handle window events?
Java Window Programming
 Solution adopted by Swing
 First, JButton object records every listener that the object informs
of pressing event.
 If JButton object is pressed, it calls actionPerformed() method of
each listener.
JButton
addActionListener()
listeners
ActionListener
actionPerformed()
Java Window Programming
 How it works
JButton
addActionListener()
listeners
ActionListener
actionPerformed()
Swing framework
Our code
Calc
actionPerformed()
Java Window Programming
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calc extends JFrame implements ActionListener {
Calc() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JButton add = new JButton("+");
JButton sub = new JButton("-");
contentPane.add(add);
contentPane.add(sub);
add.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("+ pressed");
}
public static void main(String[] args) {
...
}
+ pressed
+ pressed
+ pressed
Java Window Programming
 Handling two buttons
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calc extends JFrame implements ActionListener {
...
public void actionPerformed(ActionEvent e) {
JButton b = (JButton)e.getSource();
if (b.getText() == "+") {
System.out.println("+ pressed");
} else if (b.getText() == "-") {
System.out.println("- pressed");
}
}
public static void main(String[] args) {
...
}
}
+
+
-
pressed
pressed
pressed
pressed
public class Calc extends JFrame implements ActionListener {
JButton add = new JButton("+");
JButton sub = new JButton("-");
Calc() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(add);
contentPane.add(sub);
add.addActionListener(this);
sub.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == add) {
System.out.println("+ pressed");
} else if (e.getSource() == sub) {
System.out.println("- pressed");
}
}
public static void main(String[] args) {
...
}
}
Another way
public class Calc extends JFrame {
Calc() {
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
Yet another way
JButton add = new JButton("+");
JButton sub = new JButton("-");
contentPane.add(add); contentPane.add(sub);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addButtonPressed();
}
});
sub.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
subButtonPressed();
}
});
}
public void addButtonPressed() {
System.out.println("+ pressed");
}
public void subButtonPressed() {
System.out.println("- pressed");
}
Java Window Programming
 Other listeners







component listener
focus listener
key listener
mouse listener
mouse-motion listener
mouse-wheel listener
…
 Remarks
 Yes, look so simple!
 But it is the most effective way and, actually it’s the results of
much experience and extensive research work.
 And you will become to know that it is not easy concept at all.
OO Characteristics (rev.)
 Polymorphism
 The same operation may behave differently on different classes
 When to use concept of polymorphism
 Handling a collection of similar objects with different behavior
• e.g. PowerPoint
 Supporting the feature which will be specified in future
• e.g. toString() method, priority queue
 Coping with extension (or reuse)
• e.g. Window programming in Java (Swing)
 Important consideration by polymorphism
 Decoupling or loosely coupling
HW5: Let Your Calc Work
 Please, do not spend too much time
 No need to error check, just working is OK
 Probably, you will need the following methods




getText(), setText() of JTextField
Integer.parseInt()
String.valueOf()
consult Java API reference
Object-Oriented Development
 The essence
 Identification and organization of application-domain concepts,
 rather than final representation in programming language
• the language may be object-oriented or not
 Modeling concepts, not implementation
 Design flaws that surface during implementation are more costly
to fix than those that are found earlier
 Focusing on implementation issues too early restricts design
choices an often leads to an inferior product
 Integration, maintenance enhancement
 not explicitly addressed by this lecture
 but cleaner design in a precise notation facilitates those stages of
entire software life cycle
Object-Oriented Methodology
 Object Modeling Technique (OMT)
 Building a model of an application domain and then,
 adding implementation details to it during the design of a system
 OMT stages




Analysis
System design
Object design
Implementation
Object-Oriented Methodology
 OMT Stages
 Analysis
•
•
•
•
Starting from statement of problem
Building a model of real-world situation showing important properties
Analyst must work with requestor (client) to understand problem
Analysis model is a concise, precise abstraction of what not how
• objects should be application-domain concepts
• Good model can be understood and criticized by application experts
 System design
 Object design
 Implementation
Object-Oriented Methodology
 OMT Stages
 Analysis
 System design
• High-level decisions about overall architecture
• Organize target system into subsystems based on analysis model
and proposed architecture
• Decide what performance characteristics to optimize, choose a
strategy of attacking the problem
• e.g. communication protocol, memory buffering stratege
 Object design
 Implementation
Object-Oriented Methodology
 OMT Stages
 Analysis
 System design
 Object design
• Build design model containing implementation details based on
analysis model
• Add details regarding established strategy at system design stage
• Focus is data structure and algorithms needed to implement classes
 Implementation
Object-Oriented Methodology
 OMT Stages




Analysis
System design
Object design
Implementation
• Translate object classes into programming language, database, or
hardware
• Relatively minor and mechanical part because all of hard decisions
should be made during design
• But it is important to follow good software engineering practice for
traceability to the design, flexibility, and extensibility
Three Models of OMT
 Object model
 Describe static structure of objects in system and relationships
 Contain object diagrams which is a graph
• nodes: object classes, arcs: relationships among classes
 Dynamic model
 Describe aspects of a system that change over time
 Specify control aspect of system
 Contain state diagrams which is a graph
• nodes: states, arcs: transition between states caused by events
 Functional model
 Describe data value transformation within system
 Contain data flow diagram which is graph
• nodes: processes, arcs: data flows
Object-Oriented Methodology
 Differences from function methodology
 Functional methodology
• Focus on specifying and decomposing system functionality
• Most direct way of implementing a desired goal,
but the resulting system can be fragile
• If requirement change, maybe require massive restructuring
 Object-oriented approach
• Focus on identifying objects from application domain,
then fitting procedures around them
• Indirect, but better solution when requirements evolve
• based on underlying framework of application domain itself,
rather than ad-hoc functional requirements of a single problem
 How about it in perspective of IEer?
Object-Oriented Themes
 Abstraction
 Focus on essential, inherent aspects of entity and ignore its
accidental properties
• Focus on what is object is and does, before deciding how it should
be implemented
 Dealing only with application-domain concepts, not making
design and implementation decisions before the problem is
understood
 Encapsulation (information hiding)
 Separating external aspects of object from internal
implementation details
 Prevents interdependence between objects
• Implementation of an object an be changed without affecting others
that use it (e.g. three-dimensional point, car driving)
Object-Oriented Themes
 Combining data and behavior
 Recall polymorphism
 Class hierarchy is incorporated into method call
 Sharing
 Inheritance allows common structure to be shared among similar
subclasses without redundancy
 Classification and polymorphism
• Conceptual clarity from recognizing that different operations are all
really the same thing
 Reusing designs and code on future projects
• But remember object-orientation is not a magic formula to ensure
reusability
• We have to do it
Object-Oriented Themes
 Emphasis on object structure, not procedure
structure
 Synergy
Announcement of Quiz
 Programming test, closed-book
 Scope: homework
 Next Tuesday 13:00~14:15, computer lab.
 You have to make programming environment by yourself
including Eclipse before starting quiz
 During quiz, no program will be allowed except Eclipse and Java
API reference