540 likes | 725 Views
Introduction (3). Chapter 1 (3) Object-Oriented Modeling and Design Byung-Hyun Ha bhha@pusan.ac.kr. Lecture Outline. Introduction (rev.) Polymorphism Polymorphism examples Object-oriented development Object-oriented methodology Tree models of OMT Object-oriented themes.
E N D
Introduction (3) Chapter 1 (3) Object-Oriented Modeling and Design Byung-Hyun Ha bhha@pusan.ac.kr
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 operationmay behave differentlyon 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.*; • publicclass Farm { • staticint[] a_set; • publicstaticvoid main(String[] args) { • input(); • speak(); • } • staticvoid input() { • ... • } • staticvoid speak() { • ... • } • }
First Program • publicclass Farm { • ... • privatestaticvoid input() { • Scanner s = new Scanner(System.in); • int dogs = s.nextInt(); • int cats = s.nextInt(); • int pigs = s.nextInt(); • a_set = newint[dogs + cats + pigs]; • for (int i = 0; i < dogs; i++) { • a_set[i] = 0; // 0 means dog • } • for (int i = 0; i < cats; i++) { • a_set[dogs + i] = 1; // 1 means cat • } • for (int i = 0; i < pigs; i++) { • a_set[dogs + cats + i] = 2; // 2 means pig • } • } • }
First Program • We call it as ‘procedural way’ • publicclass Farm { • ... • staticvoid speak() { • for (int i = 0; i < a_set.length; i++) { • if (a_set[i] == 0) { • System.out.println("woof-woof"); • } elseif (a_set[i] == 1) { • System.out.println("meow"); • } elseif (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 • publicclass A { • intf1 = 3; • void m1() { • System.out.println(f1); • } • } • publicclass B extends A { • intf2 = 5; • void m1() { • f1 = f1 + f2; • super.m1(); • } • publicstaticvoid 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 • publicclass Animal { • void speak() { • System.out.println("..."); • } • } • publicclass Dog extends Animal { • void speak() { • System.out.println("woof-woof"); • } • } • publicclass Cat extends Animal { • void speak() { • System.out.println("meow"); • } • } • publicclass Pig extends Animal { • void speak() { • System.out.println("oink-oink"); • } • }
Better Program • Outline • import java.util.*; • publicclass Farm { • staticAnimal[] a_set; • publicstaticvoid main(String[] args) { • input(); • speak(); • } • staticvoid input() { • ... • } • staticvoid speak() { • ... • } • }
Better Program • publicclass Farm { • ... • privatestaticvoid input() { • Scanner s = new Scanner(System.in); • int dogs = s.nextInt(); • int cats = s.nextInt(); • int pigs = s.nextInt(); • a_set = newAnimal[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! • publicclass Farm { • static Animal[] a_set; • ... • staticvoid 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 operationmay behave differentlyon 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 • publicclass A { • publicstaticvoid 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? • publicclass Vector { • doublex; • doubley; • } • publicclass A { • publicstaticvoid 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: • Then, we should inform Java of it! • But how? (1.0,2.0)
toString() method • Add toString() method to class Vector as follows, and run again. • publicclass Vector { • doublex; • doubley; • 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’. • publicclass Vector extends Object { • doublex; • doubley; • 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 Vector toString() 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.*; • publicclass PQ { • publicstaticvoid 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. • publicclass Animal { • intage; • doubleweight; • 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.*; • publicclass PQ { • publicstaticvoid 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 • publicclass Animal implements Comparable { • intage; • doubleweight; • Animal(int age, double weight) { • this.age = age; • this.weight = weight; • } • publicint compareTo(Object o) { • Animal other = (Animal)o; • returnage - other.age; • } • public String toString() { • return"Animal: " + age + " " + weight; • } • } Animal: 1 20.7 Animal: 3 5.2 Animal: 3 9.2 Animal: 4 8.1 Animal: 5 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? • publicclass Animal implements Comparable { • intage; • doubleweight; • Animal(int age, double weight) { • this.age = age; • this.weight = weight; • } • publicint compareTo(Object o) { • Animal other = (Animal)o; • returnage - other.age; • } • public String toString() { • return"Animal: " + age + " " + weight; • } • }
Priority Queue with Our Class • publicclass Animal implements Comparable { • intage; • doubleweight; • Animal(int age, double weight) { • this.age = age; • this.weight = weight; • } • publicint compareTo(Object o) { • Animal other = (Animal)o; • double d = weight - other.weight; • if (d < 0) { • return -1; • } elseif (d == 0) { • return 0; • } else { • return 1; • } • } • public String toString() { • return"Animal: " + age + " " + weight; • } • } Animal: 3 5.2 Animal: 4 8.1 Animal: 3 9.2 Animal: 5 12.0 Animal: 1 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. listeners JButton ActionListener addActionListener() actionPerformed()
Java Window Programming • How it works listeners JButton ActionListener addActionListener() actionPerformed() Swing framework Our code Calc actionPerformed()
Java Window Programming • import java.awt.*; • import java.awt.event.*; • import javax.swing.*; • publicclass 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); • } • publicvoid actionPerformed(ActionEvent e) { • System.out.println("+ pressed"); • } • publicstaticvoid main(String[] args) { • ... • } • } + pressed + pressed + pressed
Java Window Programming • Handling two buttons • import java.awt.*; • import java.awt.event.*; • import javax.swing.*; • publicclass Calc extends JFrame implements ActionListener { • ... • publicvoid actionPerformed(ActionEvent e) { • JButton b = (JButton)e.getSource(); • if (b.getText() == "+") { • System.out.println("+ pressed"); • } elseif (b.getText() == "-") { • System.out.println("- pressed"); • } • } • publicstaticvoid main(String[] args) { • ... • } • } + pressed + pressed - pressed - pressed
publicclass 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); • } • publicvoid actionPerformed(ActionEvent e) { • if (e.getSource() == add) { • System.out.println("+ pressed"); • } elseif (e.getSource() == sub) { • System.out.println("- pressed"); • } • } • publicstaticvoid main(String[] args) { • ... • } • } Another way
publicclass Calc extends JFrame { • Calc() { • Container contentPane = getContentPane(); • contentPane.setLayout(new FlowLayout()); • JButton add = new JButton("+"); • JButton sub = new JButton("-"); • contentPane.add(add); contentPane.add(sub); • add.addActionListener(new ActionListener() { • publicvoid actionPerformed(ActionEvent e) { • addButtonPressed(); • } • }); • sub.addActionListener(new ActionListener() { • publicvoid actionPerformed(ActionEvent e) { • subButtonPressed(); • } • }); • } • publicvoid addButtonPressed() { • System.out.println("+ pressed"); • } • publicvoid subButtonPressed() { • System.out.println("- pressed"); • } Yet another way
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 operationmay behave differentlyon 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?