1 / 74

Chapter 2 – Using Objects

Chapter 2 – Using Objects. Chapter Goals. To learn about variables To understand the concepts of classes and objects To be able to call methods To be able to browse the API documentation To realize the difference between objects and object references . 2.1 Types and Variables.

libba
Télécharger la présentation

Chapter 2 – Using 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. Chapter 2 – Using Objects

  2. Chapter Goals • To learn about variables • To understand the concepts of classes and objects • To be able to call methods • To be able to browse the API documentation • To realize the difference between objects and object references

  3. 2.1 Types and Variables • Every value has a type • A type describes what category a certain piece of information falls in (number, string, bank account, etc) • 13 is an integer (int in java) • “Hello, World” is a String • 13.3 is a real (double in java) • How do we store a value for later use?

  4. 2.1 Variables • Math: A letter that represents an unknown value. y = 3x + z • CS Programming: Named space (in memory) that stores a value. Like mathematics, we can use variables to represent unknown or changing values.

  5. Variables • 4 properties to a variable • A type • A name (identifier) • Memory location • A value • 2 Decisions for declaring a variable • What type should the variable be? • What am I going to use the variable for? • What name should the variable have?

  6. Data Types • Primitive: (language defined) • Numeric • Non-numeric • Reference: (programmer defined) • Object • stores several variables that collectively represent a single entity

  7. Numerical data types • There are six numerical data types • Two sets • Integers – byte, short, int, long, • Reals/Floating Point – float, double • Difference is the range of possible values • Higher precision means larger range of values • Can be more exact with the value • What’s the tradeoff to higher precision?

  8. Integers • byte • 1 byte of information (8 bits) • Range from -128 to 127 • short • 2 bytes • Range from -32768 to 32767 • int • 4 bytes • Range from -2147483648 to 2147483647

  9. Integers • long • 8 bytes • Range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 • Which one should we use? • Why not always short? • Why not always use long? • Settle on int • Flexible • Efficient

  10. Reals • double vs. float • double really stands for double float – twice the memory • Float – up to 1038 or 7 decimal digits • Double – up to 10308 or 15 decimal digits • Floating point representation • Similar to scientific notation • Usually use double, more possible values

  11. Numbers • Do not use commas • 13,000  13000 • Can represent exponents • 1.3 x 10-4 1.3E-4

  12. Why have integers? • Why can’t we just represent all integers as floating-point? • Memory • Faster • Rounding

  13. Identifiers • Identifier: name of a variable, method, or class • Must follow Naming Standards – rules for creating identifiers • Should follow Naming conventions – make identifiers useful and readable

  14. Naming Standards (must be) • Use only: • letters • digits • _ • Cannot start with a digit • Cannot be a reserved word • Case sensitive • No spaces, punctuation

  15. Naming Conventions (should be) • Useful to follow, make program easier to read • Variables and methods start with lowercase letter. • variableName and methodName( ) • Class names should start with an uppercase • ClassName • CONSTANTS_ALL_CAPS • If two word joined, the first letter of the second word should be capitalized

  16. Declaration • Declaration: <class name> <identifiers>; <primitive> <identifier>; • Examples: • Bicycle bike; • Die die1, die2; • PopCan can1, can2, can3; • int height, width;

  17. Assignment • Assignment variableName = value; Example: • luckyNumber = 12; // luckyNumber must be able // to be set to 12 Purpose: • To assign a new value to a previously defined variable. • Assigns the value of the right side of the = to the variable on the left side • You can think of x = y as “x becomes y” or “x gets y”

  18. Assignment statement • x = 20; a = 3.5; y = 0.12; • z = x; • Don’t confuse with mathematical statement x + y = a + b; // Not valid 4+10 = x; // Not valid

  19. The first time we assign a value to a new variable, it is called initialization • If we want, we can declare and initialize a variable in one statement • <type> <identifier> = <value> • int size = 10; • Before using a variable, we must declare it and initialize it

  20. Assignment • = operator is an action to assign (replace) the a value to a variable • Not used as a statement about equality • Used to change the value of a variable int luckyNumber = 13; luckyNumber = 12;

  21. Initialization int total = 1; int memory location

  22. Initialization int total = 1; total name (identifier)

  23. Initialization int total = 1; 1 value total

  24. Assignment total = 3; 1 3 total

  25. Uninitialized Variables • Error:int luckyNumber;System.out.println(luckyNumber);   // ERROR - uninitialized variable

  26. Arithmetic • The data types discussed so far do not have methods • But we can do arithmetic operations • + - * / • Follow the rules of mathematics, including Order of Operations (with parentheses) • 10 + 2 • 10 – n • 10 * n • 2 / (1 – n)

  27. int x, y; x = 123; y = x + x; System.out.print(“Hello, Dr. Caffeine.”); System.out.print(“ x = “); System.out.print( x ); System.out.print(“ x + x = “); System.out.print( y ); System.out.print( “ THE END “);

  28. Example

  29. Mismatches • You will get an error if the value does not match the variable type • String st =13; • int x = “Go”; • The name of the variable is the identifier • Choose something useful (if storing a height, call the variable height, not h)

  30. 2.3 Objects, Classes, and Methods • The numbers we learned are primitive dataypes – represented directly in memory • No methods • Object – entity that you can manipulate in a program • Manipulated via methods – predefined functions that we can call

  31. Example • One object given to us is System.out, which is connected to the console • We can call the method println(), which manipulates the object to output a message to the screen

  32. Methods • Method: Sequence of instructions that accesses the data of an object • You manipulate objects by calling its methods

  33. Class • Class: Blueprint for objects with the same behavior • Class determines legal methodsString greeting = "Hello";greeting.println() // Errorgreeting.length() // OK • Public Interface: Specifies what you can do with the objects of a class

  34. Reference Data (Objects) • Programmers can define their own object types and create instances of those types for use in their programs. • Book, Student, BankAccount, Grade, Car, MP3Player, Phone, Course, Semester, etc…

  35. Color myFavColor Color 255 red 153 green 51 blue Components of an object • Objects contain • Data members – information the object needs to store • Methods – things the object can do • How do we represent an object?

  36. ConcreteObject • Think of an object in your backpack, purse, pocket? • Write down the type of your object. Book • Give your object a variable name and write it down next to the type. cs302Textbook • Draw a rectangle next to the name

  37. Virtual Object • Write a list of nouns or adjectives that describe your object? title = "Java Concepts" • Write a list of things that your object can do? or things that can be done to it? openToPage(x) • Draw a circle around these two lists. • Draw an arrow from the inside of the rectangle above to your circled list.

  38. You've just defined and created your first Object! We can make any object we need for our programs in much the same way.

  39. 2.4 Method Parameters • Parameter (explicit parameter): Input to a method. Not all methods have explicit parameters. System.out.println(greeting) greeting.length() // has no explicit parameter • Implicit parameter: The object on which a method is invoked System.out.println(greeting)

  40. Return Values • Return value: A result that the method has computed for use by the code that called it int n = greeting.length();//return value stored in n

  41. Passing Return Values • You can also use the return value as a parameter of another method:method composition System.out.println(greeting.length()); • Note: Not all methods return values. Example: println() • These are return type void

  42. String Methods • Concatenation • quote = “Go Badgers” + “!”; • Length • int quoteLength = quote.length(); • Index of • int find = quote.indexOf(“Badgers”); • find = quote.indexOf(“Buckeyes”); • UpperCase Converstion • String name = “apple”; • name.toUpperCase(); //”APPLE”

  43. More complex method calls • replace method carries out a search-and-replace operation river.replace("issipp", "our"); // constructs a new string ("Missouri") • What is the implicit parameter? • What is/are the explicit parameters? • a return value: the string "Missouri"

  44. Method definitions • What determines the number/type of parameters? The return value? • When a method is defined in a class, the programmer must specify • Example – String method definitions • public int length() • public void replace (String target, String replacement)

  45. Rectangle • The Rectangle class will provide an example • Does not visually create a rectangle, rather describes it numerically • (x,y) coordinate of upper-left corner • Width • Height

  46. Creating Objects • Primitives do not need to be constructed • Just declare (int x;) and use (x = 4;) • Objects cannot be used after declaring • Must also CREATE the object

More Related