Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 1 Data Types Object Interactions Tracing Introduction to Object-Oriented Programming Lesson 2: Classes and Instances.

Similar presentations


Presentation on theme: "Slide 1 Data Types Object Interactions Tracing Introduction to Object-Oriented Programming Lesson 2: Classes and Instances."— Presentation transcript:

1 Slide 1 Data Types Object Interactions Tracing Introduction to Object-Oriented Programming Lesson 2: Classes and Instances

2 Slide 2 Review

3 Slide 3  Components are objects.  The programmer determines the attributes and methods needed, and then creates a class.  A class is a collection of programming statements that define the required object  A class as a “blueprint” that objects may be created from.  An object is the realization (instantiation) of a class in memory.  Classes can be used to instantiate as many objects as are needed.  Each object that is created from a class is called an instance of the class.  A program is simply a collection of objects that interact with each other to accomplish a goal. Classes and Objects

4 Slide 4  Class  Think: generic concept  The concept of a circle  The concept of a car  The concept of a giraffe  Instance (aka Object)  Think: physical object  The green circle with a 4 cm diameter on my shirt  My blue Nissan minivan with the dent on the side  Stella, the female giraffe who lives at the Philadelphia zoo Key Concept: Class vs. Instance

5 Slide 5 DATA aka “attributes” aka “state”  For example:  Circle data: Diameter, color, (x,y) location, visibility …  Car data: Make, model, year, color …  Giraffe data: Height, weight, birthday, name … ACTIONS aka “methods” aka “functions”  For example:  Circle methods: moveDown(), changeSize(), makeVisible() …  Car methods: startEngine(), reverse(), setColor() …  Giraffe methods: eat(), walk(), sleep(),setWeight() … Classes specify types of data object store and types of actions the objects can do Object Attributes (data) Methods (behaviors / procedures)

6 Slide 6  Objects have operations which can be invoked (Java calls them methods).  Methods may have parameters to pass additional information needed to execute. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Methods and parameters 5-6

7 Slide 7  Many instances can be created from a single class.  An instance has attributes: values stored in fields.  The class defines what fields an instance has, but each instance stores its own set of values (the state of the instance). Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Other observations 8

8 Slide 8 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling State 8-9

9 Slide 9 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Two circle objects 10

10 Slide 10 public class HelloWorld { public static void main(String[] args) { String message = "Hello World"; System.out.println(message); } Programming Languages Sample Program  Key words in the sample program are:  Key words are lower case (Java is a case sensitive language).  Key words cannot be used as a programmer-defined identifier.  Semi-colons are statement terminators and are used to end Java statements; however, not all lines of a Java program end a statement.  Part of learning Java is to learn where to properly use the punctuation. public class static void Curly braces mark off a block of code

11 Slide 11  There are differences between lines and statements when discussing source code. System.out.println( message);  This is one Java statement written using two lines. Do you see the difference?  A statement is a complete Java instruction that causes the computer to perform an action. Programming Languages Lines vs Statements

12 Slide 12 Getting picky with terminology

13 Slide 13  Class versus Object versus Instance  Class is a “template” / “blueprint” that is used to create objects  Objects have two main characteristics – state and behavior. An object stores its state in fields and exposes its behavior through methods.  An instance is a unique copy of a Class. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.  Technically both classes and instances are objects.  An instance is an instantiated object derived from a class  mySquare = new Square();  Any Class in Java is actually derived from a class called Object (like objects such as arrays)  Many elements of Java are objects. Terminology Check

14 Slide 14  Instance Variable vs. Field vs. Property vs. Attribute (almost synonymous)  These terms are loosely used as synonyms.  A Field or Instance Variable is generally a private variable on a instance class. It does not mean there is a getter and setter.  Property is a field that you can get or set, typically with a getter or setter  Attribute is a vague term. It refers to anything that describes an object.  Made more confusing in that different languages sometimes use these terms a little differently. Terminology Check

15 Slide 15  Objects have operations which can be invoked  Java calls them methods  Sometimes they are called functions or procedures  Methods allow changing or accessing properties/characteristics of the object  Methods may have parameters to pass additional information needed to execute.  I may also refer to parameters as arguments  You can tell what parameters a method takes by looking at its signature.  I may also refer to signatures as prototypes Terminology: Methods 15

16 Slide 16 But slides have much greater detail Data types 7

17 Slide 17  Data in a Java program is stored in memory.  Variable names represent a location in memory.  Variables in Java are sometimes called fields.  Variables are created by the programmer who assigns it a programmer-defined identifier. ex: int hours = 40;  In this example, the variable hours is created as an integer (more on this later) and assigned the value of 40. Programming Languages Variables

18 Slide 18 Primitive data types are built into the Java language and are not derived from classes Murach’s Java Programming, C3© 2011, Mike Murach & Associates, Inc. The Eight Primitive Data Types

19 Slide 19  Variable Declarations take the following form:  DataType VariableName;  byte inches;  short month;  int speed;  long timeStamp;  float salesCommission;  double distance;  Variable Initialization occurs when the variable is set to its first value Variable Declarations and Initialization

20 Slide 20 Murach’s Java Programming, C3© 2011, Mike Murach & Associates, Inc. Initialization and Declaration of Variables SYNTAX: How to declare and initialize a variable in two statements SYNTAX: How to declare and initialize a variable in one statement

21 Slide 21  byte, short, int, and long are all integer data types.  They can hold whole numbers such as 5, 10, 23, 89, etc.  Integer data types cannot hold numbers that have a decimal point in them.  Integers embedded into Java source code are called integer literals.  Examples of integer values:  24, -46, 0, etc. Integer Data Types

22 Slide 22 Example: Integer Data Types // This program has variables of several of the integer types. public class IntegerVariables { public static void main(String[] args) { int checking; // Declare an int variable named checking. byte miles; // Declare a byte variable named miles. short minutes; // Declare a short variable named minutes. long days; // Declare a long variable named days. checking = -20; miles = 105; minutes = 120; days = 185000; System.out.print("We have made a journey of " + miles); System.out.println(" miles."); System.out.println("It took us " + minutes + " minutes."); System.out.println("Our account balance is $" + checking); System.out.print("About " + days + " days ago Columbus "); System.out.println("stood on this spot."); }

23 Slide 23  Data types that allow fractional values are called floating-point numbers.  1.7 and -45.316 are floating-point numbers.  In Java there are two data types that can represent floating-point numbers.  float - also called single precision  (7 decimal points)  double - also called double precision  (15 decimal points)  Real numbers: 43.56, 3.7e10, -3.0, -7.192e-19 Real Number Data Types

24 Slide 24  When floating-point numbers are embedded into Java source code they are called real number literals.  The default data type for floating-point literals is double.  29.75, 1.76, and 31.51 are double data types.  Java is a strongly-typed language.  Every variable must have a data type  A double value is not compatible with a float variable because of its size and precision.  float number;  number = 23.5; // Error!  A double can be forced into a float by appending the letter F or f to the literal.  float number;  number = 23.5F; // This will work. Real Number Literals (1)

25 Slide 25  Literals cannot contain embedded currency symbols or commas.  grossPay = $1,257.00; // ERROR!  grossPay = 1257.00; // Correct.  Real number literals can be represented in scientific notation.  47,281.97 == 4.728197 x 10 4.  Java uses E notation to represent values in scientific notation.  4.728197X10 4 == 4.728197E4. Floating Point Literals (2)

26 Slide 26 // This program demonstrates the double data type. public class Sale { public static void main(String[] args) { double price, tax, total; price = 29.75; tax = 1.76; total = 31.51; System.out.println("The price of the item " + "is " + price); System.out.println("The tax is " + tax); System.out.println("The total is " + total); } Example: Double Data Type

27 Slide 27 Decimal Notation Scientific Notation E Notation 247.912.4791 x 10 2 2.4791E2 0.000727.2 x 10 -4 7.2E-4 2,900,0002.9 x 10 6 2.9E6 Scientific and E Notation for Doubles // This program uses E notation. public class SunFacts { public static void main(String[] args) { double distance, mass; distance = 1.495979E11; mass = 1.989E30; System.out.print("The Sun is " + distance); System.out.println(" meters away."); System.out.print("The Sun's mass is " + mass); System.out.println(" kilograms."); }

28 Slide 28  The Java boolean data type can have two possible values.  true  false  The value of a boolean variable may only be copied into a boolean variable. The boolean Data Type // A program for demonstrating // boolean variables public class TrueFalse { public static void main(String[] args) { boolean bool; bool = true; System.out.println(bool); bool = false; System.out.println(bool); }

29 Slide 29  The Java char data type provides access to single characters.  char literals are enclosed in single quote marks.  'a', 'Z', '\n', '1‘, '\u00F6' (ö)  Don’t confuse char literals with string literals.  char literals are enclosed in single quotes.  String literals are enclosed in double quotes. The char Data Type // This program demonstrates the // char data type. public class Letters { public static void main(String[] args) { char letter; letter = 'A'; System.out.println(letter); letter = 'B'; System.out.println(letter); }

30 Slide 30  Internally, characters are stored as numbers.  Character data in Java is stored as Unicode characters.  The Unicode character set can consist of 65536 (2 16 ) individual characters.  This means that each character takes up 2 bytes in memory.  The first 256 characters in the Unicode character set are compatible with the ASCII* character set. *American Standard Code for Information Interchange Unicode // This program demonstrates the // close relationship between // characters and integers. public class Letters2 { public static void main(String[] args) { char letter; letter = 65; System.out.println(letter); letter = 66; System.out.println(letter); }

31 Slide 31 Unicode A 0065 B 0066 00000000010000100000000001000001

32 Slide 32 Unicode A 0065 B 0066 00000000010000100000000001000001 Characters are stored in memory as binary numbers.

33 Slide 33 Unicode A 0065 B 0066 00000000010000100000000001000001 The binary numbers represent these decimal values.

34 Slide 34 Unicode A 0065 B 0066 00000000010000100000000001000001 The decimal values represent these characters.

35 Slide 35 Binary Code Binary Number System: 1s & 0s  Bit –smallest unit of digital information  8 bits = 1 byte  Binary code has two possible states: on/off, 1/0, yes/no  With 8 bits there are 256 different possible combinations Copyright © 2015 Pearson Education, Inc. Number of Bits (switches)Possibilities Power of Two 122020 242121 382 4162323 5322424 6642525 71282626 82562727

36 Slide 36  The odometer model  Think of odometers in old cars or gas station pumps  Counting in base 10 How to Count 00000000 00000001 00000002 00000003 00000004 00000005 00000006 00000007 00000008 00000009 00000010 00000011 9 is the last digit. The wheel flips back to 0, and the second wheel starts to turn

37 Slide 37  Our numbers (base 10)  10 digits: 0 through 9  Binary (base 2)  2 digits: 0 through 1  Usage: How computers store data  Octal (base 8)  8 digits: 0 through 7  Usage: UNIX/Linux file permissions  Hexadecimal (base 16)  16 digits: 0 through 9, A, B, C, D, E, F  Usage: Color codes  Counting in Octal Bases © 2006 Pearson Addison-Wesley. All rights reserved 00000000 00000001 00000002 00000003 00000004 00000005 00000006 00000007 00000010 00000011 7 is the last digit. The wheel flips back to 0, and the second wheel starts to turn

38 Slide 38  Remember "places"?  Binary Base Conversions (1) the "one's" place (10 0 ) the "ten's" place (10 1 ) the "hundred's" place (10 2 ) the "thousand's" place (10 3 ) 1092 We have 2 ones We have 9 tens We have 0 hundreds We have 1 thousand 2 90 0 1000 1092 the "one's" place (2 0 ) the "two's" place (2 1 ) the "four's" place (2 2 ) the "eight's" place (2 3 ) 1011 We have 1 ones We have 1 two We have 0 fours We have 1 eight 1 2 0 8 What does the binary number 1011 translate to in base 10? base 10

39 Slide 39 HEXADECIMAL OCTAL Base Conversions (2) the "one's" place (8 0 ) the "eight's" place (8 1 ) the "sixty-four's" place (8 2 ) the "512's" place (8 3 ) 1402 the "one's" place (16 0 ) the "sixteen's" place (16 1 ) the "256's" place (16 2 ) the "4096's" place (16 3 ) 001D

40 Slide 40 public class OctalAndHex { public static void main(String args[]) { int octalEleven = 013; // Note leading zero int hexEleven = 0xB; // Note leading 0x System.out.println("Octal: " + (octalEleven + 3)); System.out.println(" Hex: " + (hexEleven + 3)); } Octal: 14 Hex: 14 Hexadecimal and Octal in Java

41 Slide 41 Object Interaction

42 Slide 42 Building a House (Answer these questions using BlueJ)  What is a class?  What is an object?  What is an instance of a class?  What are parameters to the method call?  What are the fields in a class?  What are the fields in an object?  What is the state of an object? (use the object inspector)  What are the attributes in an object’s fields?  Why are parameters specified differently for methods changeSize and changeColor?  What are the data types of the various parameters? 42

43 Slide 43  We had to create all the objects manually.  What are the next steps?  Change color of roof object to green  Move roof horizontally  Move roof vertically  Create new Circle called "sun" … Making a House (Exercise 1.9)

44 Slide 44 The house project

45 Slide 45  Project  Compile  Object Bench Additional BlueJ concepts 45

46 Slide 46  Each class has source code (Java code) associated with it that defines its details (properties and methods).  Examine code of class Circle (double click)  Examine declaration of the class fields:  private int diameter;  private int xPosition;  private int yPosition;  private String color;  private boolean isVisible;  Examine the class headers Source code 12

47 Slide 47 Object Interaction Compare figures project to house project public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); 12

48 Slide 48  New class Picture  Attributes (data)  Methods (actions) Examining a class (1) public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); Why don't we have to change the color of wall? 12-13 Here are some of the actions we did manually

49 Slide 49 public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible();  Class Header  Gives a name to the class and defines its access  Class Body  The body of a class definition. The body groups the definitions of a class's members (i.e., fields and methods) Examining a class (2) 12-13

50 Slide 50  "wall" is a property / attribute of Picture.  So is "window"  Each are instances of class Square.  "draw" is a method of picture.  "moveVertical" is a method of the instance "wall"  So is "makeVisible"  Note how these instance methods are called (invoked).  Parameters to the methods are enclosed in parentheses  Note that the Class Square is the "blueprint" which means that all square instances will have the same methods. Examining a class (3) public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); 12-13

51 Slide 51  All the methods in the house project are defined as void. This means they do not return a value; but …  … methods may return a result via a return value.  Such methods have a non-void return type.  More on this in the next chapter. Examining a class (4) public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; … public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); 14 Return value  The value returned from a method

52 Slide 52 /** * The Student class represents a student in a student * administration system. * It holds the student details relevant in our context. * * @author Michael Kalling and David Barnes * @version 2011.07.31 */ public class Student {... // Return the full name of this student. public String getName() { return name; } // Set a new name for this student. public void changeName(String replacementName) { name = replacementName; } The lab-classes project: Return Values 14 return value no return value

53 Slide 53  Objects you make and manipulate on the object bench disappear when  You quit from BlueJ  You change the source code  Source code sticks around, as long as you save it  Remember if you “save” rather than “save as” you may overwrite the book example files! What Sticks Around?

54 Slide 54  Sorry you can’t!  But you can “record” the things you would do inside a method in the source code  View terminal window  Options: record method calls Saving work you do on the object bench

55 Slide 55 Tracing a simple program

56 Slide 56  It is important that we distinguish different types of variables. Before we start tracing…

57 Slide 57  Primitive variables actually contain the value that they have been assigned. int number = 25;  The value 25 will be stored in the memory location associated with the variable number.  Objects are not stored in variables, however. Objects are referenced by variables. Primitive vs. Reference Variables number 25 int memory location

58 Slide 58  When a variable references an object, it contains the memory address of the object’s location.  Then it is said that the variable references the object. private Square wall = new Square(); Primitive vs. Reference Variables 2-58 wall Square memory location wall: Square size 120 int xPosition 170 int yPosition 140 int color "red" Str isVisible true bool

59 Slide 59  Instance Variable  A field of a class. Each individual object of a class has its own copy of such a field. public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun;...  Local Variable  A variable defined inside a method body. public static void main (String[] args) {... double discountPercent =.2; Local vs. Instance Variables

60 Slide 60 method: main Tracing local variables sc Scanner subtotal 500 double a Scanner object “scrap paper”

61 Slide 61 Two circle objects: Book notation

62 Slide 62 Tracing Instance Variables circle_1: Circle diameter 50 int xPosition 80 int yPosition 30 int color "blue" Str isVisible true bool circle_2: Circle diameter 30 int xPosition 230 int yPosition 75 int color "red" Str isVisible true bool I note the type of each field Book Notation:

63 Slide 63 Things to note about code presidentObama.makeVisible(); presidentObama.slowMoveHorizontal(60); presidentObama.changeSize(120, 60); 63 All lines end with a semicolon This looks like source code we will eventually be writing ourselves When executing a method we always write: objectName.methodName(parameters);

64 Slide 64 Inspecting myPicture: BlueJ 64

65 Slide 65 Inspecting myPicture: BlueJ 65

66 Slide 66 Inspecting myPicture: BlueJ 66

67 Slide 67 My notation wall: Square size 120 int xPosition 170 int yPosition 140 int color "red" Str isVisible true bool window: Square size 40 int xPosition 190 int yPosition 160 int color "black" Str isVisible true bool roof: Triangle height 60 int width 180 int xPosition 230 int color "green" Str isVisible true bool yPosition 80 int sun:Circle diameter 80 int xPosition 330 int yPosition 50 int color "yellow" Str isVisible true bool myPicture:Picture wall Square window Square roof Triangle sun Circle

68 Slide 68 Looking at the Picture Class  Names of all of the fields in the class seem to be listed at the top of the code public class Picture { private Square wall; private Square window; private Triangle roof; private Circle sun; myPicture:Picture wall Square window Square roof Triangle sun Circle

69 Slide 69 Looking at the Picture Class public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); Create a new instance of the Square class called “wall” Do the setup for “wall” Setup for all of the fields seems to be inside the draw method wall: Square size 120 int xPosition 170 int yPosition 140 int color "red" Str isVisible true bool

70 Slide 70 Looking at the Picture Class public void draw() { wall = new Square(); wall.moveHorizontal(-140); wall.moveVertical(20); wall.changeSize(120); wall.makeVisible(); window = new Square(); window.changeColor("black"); window.moveHorizontal(-120); window.moveVertical(40); window.changeSize(40); window.makeVisible(); Next, create a new instance of the Square class called “window” Do the setup for “window” wall: Square size 120 int xPosition 170 int yPosition 140 int color "red" Str isVisible true bool window: Square size 40 int xPosition 190 int yPosition 160 int color "black" Str isVisible true bool

71 Slide 71  Java Requirements:  Identifiers must consists of letters, digits, underscore ( _ ) or dollar sign ($)  Identifiers must start with a letter - cannot start with digit  Java Conventions (and my requirements):  Class names start with capital letter - Use PascalCasing  Method / variable names should be clear and descriptive – Use camelCasing  Avoid one letter and meaningless identifier names Naming 71

72 Slide 72 Looking Closer at the Code: Method Signatures General Pattern Seems to Be: public void methodName(sometimes parameters here) Examples from Triangle classes in figures example : public void makeVisible() public void moveRight() public void moveHorizontal(int distance) public void changeSize(int newHeight, int newWidth) public void changeColor(String newColor) 6-7

73 Slide 73 Demo  Open Lab-classes project  Make a new student  Hey – this method takes parameters!  Try the getName method  Returns a value  Change the student’s name & getName again  Look at Student Class Methods  Can we tell which return values?

74 Slide 74 General Pattern: public returnType methodName(sometimes parameters here) Examples from Triangle class in figures example : public void makeVisible() public void moveHorizontal(int distance) public void changeSize(int newHeight, int newWidth) Method Signatures 74 Void means: “This space intentionally left blank” 6-7

75 Slide 75 General Pattern: public returnType methodName(sometimes parameters here) Examples from Triangle class in figures example : public void makeVisible() public void moveHorizontal(int distance) public void changeSize(int newHeight, int newWidth) Examples from Student class in figures example : public String getName() public int getCredits() public String getStudentID() public void addCredits(int additionalPoints) public void changeName(String replacementName) Method Signatures 6-7

76 Slide 76 public returnType methodName(sometimes parameters here) returnType can be:  primitive data type (like int or float or double or char)  class (like Circle or Student) or  void (no return value) Return values 76 14

77 Slide 77 Parameters public returnType methodName(sometimes parameters here) parameters are:  Separated by commas Each parameter consists of  &   Can be a primitive data type or a class   The alphanumeric name of the parameter

78 Slide 78 IOOP Glossary Terms to Know Terms to know for tests/quizzes (see class web site) argumentbinarybooleanclass bodyclass header data typedecimalfloating-point number hexadecimalinstance variable integerlocal variablemembermethodmethod body method headermethod resultmethod signature octalparameter primitive typereal numberreturn statement return typereturn value Non-glossary terms to know initializationdeclarationproperty Note:the glossary definitions are complete ones, based on a full understanding of the material which we might not yet have. However, there are elements of the definitions that you should be able to grasp from this material.


Download ppt "Slide 1 Data Types Object Interactions Tracing Introduction to Object-Oriented Programming Lesson 2: Classes and Instances."

Similar presentations


Ads by Google