440 likes | 534 Views
ITM 352 Object Oriented Concepts, Types, Strings, Simple I/O Lecture #3. Announcements. Assignments Assignment 1 will be posted on web site http://www2.hawaii.edu/~dport/ITM352_S03/Assignments/Asst_1.doc, due 1/28 Start now, finish early!!! Guest lecturers
E N D
ITM 352Object Oriented Concepts, Types, Strings, Simple I/OLecture #3
Announcements • Assignments • Assignment 1 will be posted on web site http://www2.hawaii.edu/~dport/ITM352_S03/Assignments/Asst_1.doc, due 1/28 • Start now, finish early!!! • Guest lecturers • There will be guest lecturers from time to time • 2/3, 2/6 – Anothony Wong • 2/11, 2/13 – Phillip Johnson (from CS) • Please attend class these dates and bug them with questions!
Agenda • Brief Review • Lecture: • Introduction to OOP concepts • Variables • Types • Strings • Simple I/O
Programming: algorithms Task { // move around wall Karel.move(); Karel.turnRight(); Karel.move(); Karel.move(); Karel.turnLeft(); Karel.move(); } May not work!!! ?
Programming: algorithm pseudocode Turn right; If facing a wall? then turn left and if facing a wall? then turn left and if facing a wall? Then turn left and if facing a wall? Then …
Programming: completion If ( Karel.InBox() ) { Karel.turnRight(); while( Karel.isFacingWall() ) { Karel.turnLeft(); } Karel.move(); }
Qualities of algorithms An algorithm must: • Be unambiguous • Executable (compact) • Terminate (converge)
Source file layout (cont.) • Choose layout for readability. • Note how brackets of various types tend to match up - layout should make this clear class Hello { // Author: Dr. Chandra public static void main (String[] args) { System.out.println(“Hello!”); } // end of main } // end of class
Technology System Realm of Actions to Realm of Representations • Realm of actions and possibilities - • People • General System Concept faithful A translation process: - informal to formal - abstract to concrete - course grain to fine grain • Realm of representations - • Technology • Specific
Short Introduction to OO We’ll go into greater depth on this later, today just some concepts to meditate on
Data vs. Information • Data: collection of facts or results • Ex. Raw scores on an exam • Information: processed data (significance is assigned by an audience) • Has an intended meaning with context and relationships directed toward a particular audience • Ex. Average score on an exam
Data Object name and fields Event objects Interface implementation Argument to a method Attribute value Exception Objects Information Result of some computations Typing an object with an interface Caller of a method Attribute owner Exception name used in a catch block Example: Java Data and Information
Information vs. Encapsulation • Putting bits in a bucket gives you a bucket of bits (easier to carry, but still data) • Encapsulation hides complexity such as implementation details • Encapsulation itself does not necessarily add information • Information always has intended meaning
Example: Information and Encapsulation • A Clock: • Information - The current time relative to a place on earth with respect to its rotation • Abstraction - Represents time through it’s defining qualities (year, day, hour, minute, second, alarm) • Encapsulation - The display is an interface to hide the complexity of the mechanics (chips, gears, atomic vibrations, net time, etc.)
Interfaces and Information • Abstractions provide interfaces to their data and behaviors • Represented information is accessed by interacting with an abstraction’s interface, not with the abstraction itself • Rule: Interfaces must be smaller than the information they represent, • interfaces set the context for presenting information
Example: Interfaces • A clock has a display, knobs, etc. • You don’t tell time by looking at the gears or reading the chip impulses directly • The time information is accessed by interacting with its display, knobs, etc.
Attributes Object Abstractions • An abstraction that represents both memory and functionality • memory: resolution of a component’s static qualities such as attributes and relationships. • Functionality: set of methods that embody operations Behaviors
Behaviors Behaviors Behaviors Attributes Attributes Attributes Object Encapsulation • Objects “hide” data (in attributes) from other objects behind an interface • this is known as encapsulation ?
Behaviors Behaviors Behaviors Attributes Attributes Attributes Encapsulation is Useful • This is useful as is reduces the complexity of your system by breaking in into focused parts. You do not need to know exactly how another object handles its behaviors and attributes !
Behaviors Behaviors Behaviors Attributes Attributes Attributes Object Relationships • Objects interact (share data, invoke operations) through relationships relation3 relation1 relation2 kool!
Objects • Represent the way people usually abstract everyday ideas and structures • Let software developers concentrate more on real world processes rather than computer processes • Help hide technical complexities • Support reuse of intuitive collection of code and software systems
Objects and Class • Directly describing object structures is inefficient • many objects have the same qualities, just different quality resolutions • Java uses the concept of a Class to group the same “type-of” objects together • A Class contains the description on how to create objects of particular type. Sometimes called a “factory object” or “metaobject” • Objects are constructed (instantiated) through their Class definitions
Classes and objects • Every class has objects, or instances, created using the newoperation. Think of the class as an object-producing machine. aRobot Robot anotherRobot new aTextField TextField new anotherTextField
Java Objects • Literally an instance of a Class (which shockingly is itself, an object!) • Class defines and creates (instantiates) an object • always have a reference after instantiation • Behaviors are instance methods • methods contain operations • do not have to accept or return values • Attributes are instance variables • all variables must be typed • defined outside of any method
Java Block Syntax • Blocks are special groupings in Java • used to isolate (encapsulate) collections of items that are viewed as a single item from outside the block • creates “parts” and “partitions” • are always delimited at the head by “{“ and tail by “}” • Ex.{ System.out.println(“this item”); System.out.println(“and this item”); System.out.println(“are in the same block)” } • may or may not be named • often are nested • all Java structures use the block syntax
Nested and Named Block { System.out.println(“outside block item1”); System.out.println(“outside block item2”); { // head inside System.out.println(“inside block item1”); System.out.println(“inside block item2”); { // head inside-inside System.out.println(“inside-inside block item1”); System.out.println(“inside-inside block item2”); } // tail inside-inside } // tail inside } // tail outside (question: does the above blocks do anything?) • Important that all blocks are balanced • each head has a tail • big source of bugs are incorrect block delimiters
Java Class Structure Class name Class Robot { // head of class definition /* Author: Dr. Chandra * This is the a very stupid Robot * used for test purposes */ String name; printName(String aName) { // head of method def System.out.println(“My creator calls me “+name); } // tail of method def } // tail of method def Instance variable Instance method Method call or operation
A bit of a puzzle... • What is the “first”class? • What is the first object? • How is it instantiated?
Puzzle Solution $ Java RobotTest class RobotTest { // Author: Dr. Chandra // another stupid test public static void main (String[] args) { Robot myRobot = new Robot(); System.out.println(“Hello!”); } // end of main } // end of class JVM implicitly does new for JVM looks for this Instantiates a Robot from the Robot.class and assigns its reference to myRobot
Classes: Summary • Describe objects of the same type (type-of) • Some qualities • behaviors (methods) • attributes (instance variables) • constraints • Many possible quality resolutions - maintained in objects • Describe how an object of a given type is created (instantiated) in any given situation (instance)
Chapter 2 Primitive Types and Simple I/O Primitive Data types Strings: a class Assignment Expressions Keyboard and Screen I/O Documentation & Style
What is a program variable? • A named location to store data • a container for data • It can hold only one type of data • for example only integers, only floating point (real) numbers, or only characters
Creating Variables • All program variables must be declared before using them • A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: Type Variable_1, Variable_2, …; • For example, to create three integer variables to store the number of baskets, number of eggs per basket, and total number of eggs: int numberOfBaskets, eggsPerBasket, totalEggs;
Assigning Values to Variables • The assignment operator: “=“ • the “equals sign” • Not the same as in algebra • It means -“Assign the value of the expression on the right side to the variable on the left side.” • Can have the variable on both sides of the equals sign: int count = 10;// initialize counter to ten count = count - 1;// decrement counter • new value of count = 10 - 1 = 9
An Expression Can Be • 1. An identifier (constant, variable, object, or method) • A number constant: amount = 3.99; • A string constant: strName = “ITM352”; • A character constant: gender = ‘M’; • A variable: score = cards • A method or an object: strName = SavitchIn.readLine(); strMyName = strFirstName; • 2. An arithmetic or complicated expression: • score = cards + value - 8; • 3. Boolean expression, which always return either true or false • If( testScore > finalExamScore) • An expression always returns a value. • Note that expressions are always on the right hand side of the assignment operator in a assignment statement.
Constants Constants cannot change their values. • character: ‘a’, ‘A’, ‘(‘ • String: “ITM 352”, “Application” • integer: 1, 2, 1999 • floating-point: 1.11, 2.897, 100.01
Assigning Initial Values to Variables Initial values may or may not be assigned when variables are declared: The first time you assign a value to the variable is called initialization. //These are not initialized when declared //and have unknown values int totalEggs, numberOfBaskets, eggsPerBasket; //These are initialized to 0 when declared int totalEggs = 0; int numberOfBaskets = 0; int eggsPerBasket = 0; • Programming tip: it is good programming practice always to initialize variables.
Changing the Value of a Variable • Usually the value is changed (assigned a different value) somewhere in the program • May be calculated from other values: totalEggs = numberOfBaskets * eggsPerBasket; • or read from keyboard input: totalEggs = SavitchIn.readLineInt();
Rules- these must be obeyed all Java identifiers must follow the same rules must not start with a digit must contain only numbers, letters, underscore (_) and $ (but avoid using $, it is reserved for special purposes) names are case-sensitive (ThisName and thisName are two different variable names) Good Programming Practice- these should be obeyed always use meaningful names from the problem domain (for example, eggsPerBasket instead of n, which is meaningless, or count, which is not meaningful enough) start variable names with lower case capitalize interior words (use eggsPerBasket instead of eggsperbasket) avoid using $ since it is reserved for special purposes Variable Names: Identifiers
primitive data types also call primitive types or basic types the simplest types cannot decompose into other types values only, no methods Examples:int - integerdouble - floating point (real)char - character class data types also call class types more complex composed of other types (primitive or class types) both data and methods Examples:SavitchInString Two Main Kinds of Types in Java
int just whole numbers may be positive or negative no decimal point char just a single character uses single quotes for examplechar letterGrade = `A`; double real numbers, both positive and negative has a decimal point (fractional part) two formats number with decimal point, e.g. 514.061 e (or scientific, or floating-point) notation, e.g. 5.14061 e2, which means 5.14061 x 102 Which Ones to Know for Now Display in text is for reference; for now stick to these simple primitive types:
Assignment 1 • Read • Savitch: Ch.2.1, 2.2, 2.3 • Program • Find out what day of the week you were born on • Easy program, just follow the steps in the flowcahrt. Start as you did with Lab 1 but change the names (and locations) • Assignment purpose is to use JBuilder, simple I/O (SavitchIn), Strings, expressions, variables, and ??? • Start working on it now!