1 / 110

Modelling Objects

Today's Lesson Plan. Discuss labs, quizzes, and TDA topics (30 min)Lackluster discussion/online participation by someImportance of deadlinesFinish work on time don't fall behind!Class Activities covers Chapter 3

laszlo
Télécharger la présentation

Modelling Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. Modelling Objects Chapters 3 & 10 Overview

    2. Todays Lesson Plan Discuss labs, quizzes, and TDA topics (30 min) Lackluster discussion/online participation by some Importance of deadlines Finish work on time dont fall behind! Class Activities covers Chapter 3 & 10 (95 min) Visually show how to create UML class and object diagrams (using Visio, dia, etc.) and Java classes with attributes, behaviours, etc. using an IDE. (25 min) Show visually the syntax and structure of a Java method and discuss how to send messages. (25 min) Discuss method overloading and other method characteristics, like passing parameters, returning values, etc. Conduct activities & break (25 min) Create a GUI program that uses event handling methods. (25 min) Coding Exercises (90 min) Code Ex 1 p 539 # 10.3.5 Code Ex 2 p 540 # 10.3.8 (a & b) Code Ex 3 p 560 # 10.5.5 and 10.5.6 (a & b) Wrap-up (20 min) Review key learning outcomes (10 min) Introduce weeks homework assignment and submission policy (5 min) Introduce online topic for discussion and Threaded Discussion posting expectations (5 min)

    3. Users Software Expectations Users have come to expect software to have greater functionality Windows-based graphical user interface Transparent access to data stored in mini or mainframe computers The ability to work in a network environment

    4. Object Oriented Programming Faced with this complexity, software engineers developed OOP as a new way of organizing code and data More programmers are starting to use Object Oriented Programming (OOP).

    5. Introduction to OOP OOP promises increased control over the complexity of the software development process. The underlying concepts of OOP are, Data Abstraction with Encapsulation Inheritance Polymorphism

    6. Encapsulation : This is the mechanism that binds together code and data it manipulates, and keeps both safe from outside interferences and misuse. Inheritance : This is the process by which one object acquires the properties of another object. This supports the concept of hierarchical classification. Polymorphism : This is a feature that allows one interface to be used for a general class of actions. OOP

    7. Evolution of OOP Languages

    8. Evolution SIMULA67 gave us the crucial Object oriented concepts of classes, dynamic objects, encapsulation and inheritance. Smalltalk is another OOP Language and environment released in 1980. C++ first version 1983 Eiffel in 1988 -not an extension of an existing procedural language syntax

    9. Introduction to Java Java was developed by James Gosling at Sun Microsystems in 1991. His Original Aim was to develop a low cost, Hardware Independent Language based on C++. Due to technical reasons that idea was dropped . A new programming Language called Oak was developed based on C++ .

    10. Introduction to Java Contd....

    11. The World of Objects The World consists of Objects Objects are Nouns A System of Objects is usually what we want to simulate or implement with a program on a computer

    12. Example Class Scheduling System Assign students to classes Objects include: Professors Students Classes Time slots Rooms

    13. Another Example Graphical Drawing System Allow user to draw shapes and manipulate them on the screen Objects include: Circles Rectangles Lines Polygons Pens

    14. Objects have a State Attributes

    15. Objects Can Do Things Methods

    16. Objects Can be Sent Messages

    17. Basic Objects Objects are the things in the world (Nouns) Attributes Properties each of those things have Methods Actions that each of those things can do Message Communication from one object to another, asking for a method to be used; the way methods are triggered

    18. Example Bank Accounts Bank accounts have a state attributes, like owner, balance, kind of account Bank accounts (in OOP) can do things methods, like deposit( ) and withdraw( ) Each bank account is represented by an object Send an object a message to get it to add or subtract money

    19. Lets Consider Shapes Shapes can do things methods Shapes have a state attributes Attributes of a shape: Filled, line width, line color, fill color, location Methods of a shape: Fill, Empty, Move, Grow

    20. Fun with Shapes Each Shape is an Object

    21. There is a Structure Here There are certain shapes of a related kind This prototype is called a Class

    22. Each Object is an Instance of a Class An Instance of the Class Circle Two Instances of the Class Square An Instance of the Class Line

    23. Classes A Class is an abstract description of objects having the same attributes and methods A specific Object is an instance of a Class A Class is the cookie cutter An Object is the cookie

    24. Many Different Objects from a Single Class

    25. How Do We Create an Object? We use a constructor This takes a Class and creates an Instance of the class, an object, perhaps with certain properties Construct an Instance of the Class Person, give it the name bill, and make its Age be 47, its Height be 177 cm, and its Weight be 68 kg.

    26. How Do We Create an Object? Presto! We now have an object bill, with certain attributes, and with the method Move The object bill can now be sent the message Move

    27. Object Vocabulary Classes Prototypes for objects Constructor Given a Class, the way to create an Object (that is, an Instance of the Class) and initialize it Objects Nouns, things in the world Attributes Properties an object has Methods Actions that an object can do Messages Communication from one object to another, asking for a method to be used

    30. Program Development

    31. Compilation

    32. Compilation and Execution in Java

    33. Programming Errors Programming errors can be classified into four broad categories: Lexical (Syntactic) Errors Execution (Run-time) Errors Intent (Semantic) Errors

    34. Lexical Errors A lexical error occurs whenever we type a word not in the vocabulary:

    35. Syntactic Errors A syntactic error occurs when we use incorrect grammar or punctuation:

    36. Bugs and Debugging All types of errors are known as bugs Debugging means removing errors from a program Lexical (Syntactic) errors can be discovered when (trying to) compile Execution (Run-Time) errors can be discovered when (trying to) run the program Intent (Semantic) errors can sometimes be hardest to find

    37. Program Development

    38. Introduction to Swing Java GUI Classes, Applications, & Applets

    39. AWT to Swing AWT: Abstract Windowing Toolkit import java.awt.* Swing: new with Java2 import javax.swing.* Extends AWT Tons o new improved components Standard dialog boxes, tooltips, Look-and-feel, skins Event listeners API: http://java.sun.com/j2se/1.3/docs/api/index.html

    40. GUI Component API Java: GUI component = class Properties Methods Events

    41. Using a GUI Component Declare it Declare object: JButton b; Create it Instantiate object: b = new JButton(press me); Configure it Methods: b.setText(press me); Add it panel.add(b); Listen to it Events: Listeners

    42. Anatomy of an Application GUI

    43. Using a GUI Component 2 Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it

    44. Build from bottom up Create: Frame Panel Components & their Listeners Add: (bottom up) listeners into components components into panel panel into frame

    45. Code JFrame f = new JFrame(title); JPanel p = new JPanel( ); JButton b = new JButton(press me); p.add(b); // add button to panel f.setContentPane(p); // add panel to frame f.show();

    46. Application Code import javax.swing.*; class hello { public static void main(String[] args){ JFrame f = new JFrame(title); JPanel p = new JPanel(); JButton b = new JButton(press me); p.add(b); // add button to panel f.setContentPane(p); // add panel to frame f.show(); } }

    47. Layout Managers Automatically control placement of components in a panel

    48. Layout Manager Heuristics

    49. Combinations

    50. Combinations

    51. Code: null layout JFrame f = new JFrame(title); JPanel p = new JPanel( ); JButton b = new JButton(press me); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null); // x,y layout p.add(b); f.setContentPane(p);

    52. Code: FlowLayout JFrame f = new JFrame(title); JPanel p = new JPanel( ); FlowLayout L = new FlowLayout( ); JButton b1 = new JButton(press me); JButton b2 = new JButton(then me); p.setLayout(L); p.add(b1); p.add(b2); f.setContentPane(p);

    53. Applets JApplet is like a JFrame Already has a panel Access panel with JApplet.getContentPane() import javax.swing.*; class hello extends JApplet { public void init(){ JButton b = new JButton(press me); getContentPane().add(b); } }

    54. Applet Methods Called by browser: init() - initialization start() - resume processing (e.g. animations) stop() - pause destroy() - cleanup paint() - redraw stuff (expose event)

    55. Application + Applet import javax.swing.*; class helloApp { public static void main(String[] args){ // create Frame and put mainPanel in it JFrame f = new JFrame(title); mainPanel p = new mainPanel(); f.setContentPane(p); f.show(); } } class helloApplet extends JApplet { public void init(){ // put my mainPanel in the Applet mainPanel p = new mainPanel(); getContentPane().add(p); } } // my main GUI is in here: class mainPanel extends JPanel { mainPanel(){ setLayout(new FlowLayout()); JButton b = new JButton(press me); add(b); } }

    56. Applet Security Applets are in a sandbox No read/write on client machine Cant execute programs on client machine Communicate only with server Java applet window Warning

    57. UML to Classes How we actually make objects (FROM OOP OVERVIEWS END)

    59. Inheritance Extending Base Classes

    60. Introducing Inheritance In real situations either when modeling real world objects such as vehicles, animals, etc. or when modeling abstract data structures such as queues, stacks, collections, windows, menu boxes the structure of different object families can be viewed as a kind of family tree. Most OO languages allow us to use these types of relationships to reuse code and functionality by making classes that use characteristics of parent classes We are going to cobble together these ideas using Java classes, just to illustrate the basic ideas.

    61. Defining the Differences Classes often share capabilities. We want to avoid re-coding these capabilities. Reuse of these would be best to: Improve maintainability, Reduce cost, Improve real world modeling.

    62. Inheritance Defined When one class re-uses the capabilities defined in another class. The new subclass gains all the methods and attributes of the superclass.

    63. Benefits of Inheritance Saves effort of reinventing the wheel. Allows us to build on existing code, specializing without having to copy it, rewrite it, etc. To create the subclass, we need to program only the differences between the superclass and the subclass that inherits from it. Allows for flexibility in class definitions.

    64. How do we Get a Robot that Has New Methods? We create a new Class that extends the BasicRobot Class The new Class inherits all of the methods and attributes of the BasicRobot Class, but then adds new methods of its own Then we use the new Class to create instances of robots, with the new methods

    65. Inheritance

    66. Inheritance Class 1 is more general, less specific Classes 2 and 3 have more methods and attributes

    67. Class Hierarchy (showing Attributes, not Methods)

    68. Constructing Objects The objects we create, using a constructor, can be from any of those classes (though the most specific ones might be the most useful) We can make a Cheerios box object or a Corn Flakes box object from the Cereal Boxes class But we might also make just a box object from the Boxes class

    69. The Details, Defining a new Method, moveMile, inside a new class

    70. The Details, Defining a new Method, moveMile, inside a new class

    71. Visually, What Have We Got?

    72. Two Types of Inheritance Extension Adds attributes Adds methods Redefinition (Method Overriding) Changes/modifies existing methods, specializing as needed

    73. Consider our primitive BankAccount that allows only three kinds of transactions: Deposits, Withdrawals, Ability to check current balance. Inheritance Example: Bank Accounts

    74. The Base Class BankAccount

    75. Inheritance by Extension Imagine that we wish to have a new kind of Bank Account that is: Identical to the base class in all respects, except one We want to add the ability for the account to earn interest Without inheritance, wed have to write it from scratch, duplicating code, etc. With inheritance, we need code only the new capability and inherit the rest.

    76. Illustration of Inheritance by Extension

    77. SavingsAccount Documentation

    78. Inheritance by Redefinition Imagine that we wish to create a new kind of Savings Account that is identical to Savings Account in all respects, except: We want to change the way in which withdrawals are handled The base class already handles withdrawals, but now we want a subclass that does them differently. Without inheritance, wed have to rewrite it from scratch. With inheritance, we need code only the new way that we want withdrawals to work

    79. Illustration of Inheritance by Redefinition

    80. Documentation for DeluxSavings Account

    81. The Story So Far OO allows us to encapsulate behavior: Methods (functions to manipulate the data) Attributes (local data) Public methods (accessible to any user) Protected methods (accessible only to child classes) Private methods (internal use only) Inheritance allows us to: Derive more specific classes from a general class By extension adding attributes and methods By redefinition changing methods Use protected access to the parents data and/or methods

    82. An Important Distinction There are two different kinds of relationship between objects: Inheritance (IS-A) relationship where a child object inherits characteristics of the parent object Parent class: Vehicle Attributes: location, speed, length, people Child class: Van Attributes: all above plus cargo capacity Containing (HAS-A) relationship where the data part of an object is a collection of other objects Container: Queue Internal structure: dont care Items contained: anything you put in there Special classes derived from queues might have methods that restrict the nature of the items in the queue

    83. Closer to what we wanted

    85. Modeling Objects

    86. The Base Class BankAccount

    87. Documentation for the BankAccount Class

    89. The Robot World

    90. Robot Capabilities Any mobile robot Can move forward Can turn in place Can pick up and put down beepers into his beeper bag

    91. Programs When we want a Robot to do something, we send it a detailed sequence of messages how to do it There exists a Controller that receives, memorizes, and follows instructions These instructions are called a program

    92. Programming Language Instructions are given in a special language It has a vocabulary, punctuation marks, and rules of grammar The language allows us to write brief and unambiguous programs

    93. Tasks and Situations A task is something we want a Robot to do move to a particular corner, escape from a maze, find a beeper and deposit it on the origin A situation is an exact description of the Robots world What corner are Robots on? What directions are they facing? What is the location and size of each wall section in the world? What is the location of each beeper (including the number of beepers in robots beeper bags)?

    94. The BasicRobot Class This is the class that can be used to create instances of actual Robots in the robot world It has five methods: move turnLeft pickBeeper putBeeper turnOff Lets look at each of them

    95. pickBeeper A robot executes a pickBeeper by picking up a beeper from the corner he is on and putting it in his bag If there is no beeper there, he performs an error shutoff If there is more than one beeper, he randomly picks up one and puts it in the bag beepers are small; they never block movement

    96. turnOff When a robot executes a turnOff, he turns himself off and does not execute any more instructions until he is restarted on another task The last message in every robot program must be a turnOff message

    97. The BasicRobot Class This class has not only five methods, but also four attributes x-location y-location direction num-beepers Each has the obvious meaning

    98. None of these Attributes or Methods Exist in Isolation We use the Class BasicRobot to create an instance of a robot The instance is created using a constructor; that gives the robot a name and sets it up in an initial situation (that is, with initial attributes) We send messages to the instance, telling it what to do

    99. Creating an Instance

    100. An Instance of BasicRobot So lets say we want to create an instance of BasicRobot, called bill, standing at Avenue 2, Street 6, facing East, with 1 beeper in his bag We write BasicRobot bill = new BasicRobot(2, 6, East, 1); Now, to get bill to move, we would write bill.move( ); That is, we send bill a move message, and he moves

    101. BasicRobot bill = new BasicRobot(2, 6, East, 1);

    102. Primitive Instructions and Simple Programs We get a robot to execute an instruction by sending it a message with the associated action We execute a program by executing each instruction in the program A program is made up of interactions amongst different objects

    103. A Robot Program for the Task import intro2cs.utils.*; class MoveRobot { public static void main(String[ ] args) { BasicRobot bill = new BasicRobot(2, 2, East, 0); bill.move( ); bill.move( ); bill.pickBeeper( ); bill.move( ); bill.turnLeft( ); bill.move( ); bill.move( ); bill.putBeeper( ); bill.move( ); bill.turnOff( ); } }

    104. Steps to Nirvana Type the program into a file named MoveRobot.java (case matters; really) Compile it javac MoveRobot.java Execute it java MoveRobot

    105. Reserved Words Used to structure and organize the primitive instructions in the robot language We have already seen reserved words in our program main and new

    106. Semicolons Semicolons terminate messages (instructions)

    107. Indentation Indentation makes programs easier to read, so get in the habit. Delimiters (the braces) and the part they delimit are indented

    108. Execution Errors Execution errors occur when your program is not able to correctly execute a task:

    109. Intent Errors The worst of all. The robot successfully completes his program, but not his task. An intent error may occur early in a program and lead to an execution error later on. Then, we must trace backward from the instruction that caused an error shutoff, to find the instruction that started the robot in the wrong direction.

    110. Intent Error A simple intent error:

More Related