1 / 23

Objects and Classes

Objects and Classes. Plan for Today - we will learn about: the difference between objects and primitive values how to create (or construct ) objects some specific types of objects: Strings Scanner objects Random objects. Using and Creating Objects. We already know about:

jaunie
Download Presentation

Objects and Classes

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. Objects and Classes Plan for Today - we will learn about: • the difference between objects and primitive values • how to create (or construct) objects • some specific types of objects: • Strings • Scanner objects • Random objects

  2. Using and Creating Objects • We already know about: • variables - store data • methods - carry out operations and represent behavior • types - categories of data (double, int, char, etc) • Object: an entity in programs that ties together data and operations. • An object contains: • Variables that store its data • Methods that carry out its actions • Example: a RockStar class • Data/Variables: tourSchedule, bandName, monthlyEarnings, musicStyle • Methods/actions: tour(), perform(), record()

  3. Objects • Manipulate an object by calling methods on it: • System.out is an object - manipulate it by calling method print() or println(): • System.out.println(“Hello World”); • The identifier out is an object stored in the System class, and println() is a method we can call on the object out. • Create an object by using the new operator and a special method called a constructor. Scanner scan; // set aside memory to hold address of Scanner object scan = new Scanner(System.in); // new operator + invoking constructor

  4. Variables in Java • In Java, a variable name represents either: • a primitive value, or • an object • Reference variables, which represent objects, hold a reference (an address in memory) to objects (or the value null to indicate that no object is referenced). • Unlike variables of a primitive type, references do not hold values directly. They hold pointers (ie, memory addresses). RockStar lennon = new RockStar(“John Lennon”); 1024 lennon bandName tourSchedule ... 1024

  5. Declaring Reference Variables • Declaration of object variables looks similar to declarations of primitive variables: • double num; // creates variable that holds a real number • String myName; // creates a String variable that will hold the address in memory of a String. • To initialize these variables: • num = 15; • myName = new String(“Mary”); myName memory address 2048 num 2048 15 “Mary”

  6. Creating a New Object • To create a new object, declare a variable of the reference type to store the object’s location, and construct the new object by using the new operator and invoking the constructor. Assign the new object’s address to the reference variable: <refType> <varName> = new <refType> (<arguments>); Examples: Point origin = new Point(0, 0); String teacher = new String(“Sensei”); Scanner reader = new Scanner(System.in);

  7. Shortcut: For Creating String Objects • Strings are used very frequently, so we have this shortcut for creating a new String object without using the new operator and constructor: String author = “Reges and Stepp”; • This is for Strings only, and is equivalent to: String author = new String(“Reges and Stepp”);

  8. Reassigning Value of a Reference Variable • Since an object variable holds an address, assigning the value of one object variable to another is different from the same sort of assignment with primitive type variables. Example: What happens? int num1 = 33; int num2 = 45; num2 = num1; Note: num1 and num2 still refer to different locations in memory. Example: What happens? (Hint: 2 references to same object) String name1 = “Anakin”; String name2 = “R2D2”; name2 = name1;

  9. Strings • A String object represents a sequence of characters • String literals are enclosed in double quotes • String creation: • String <varName> = “<your text here>”; • String <varName> = new String(“<your text here>”); • Calling methods on a String: String myName = “Al Gore”; int len = myName.length(); // len is 7 int anotherLength = “Charlie Boy”.length(); // anotherLength is 11 • To call a method on an object: • <varName>.<methodName>(<arguments>); • Methods that are part of an object are not static methods.

  10. String Indexing • The characters in a String each have an index or position, starting with index 0 for the first character. String greet = “so long”; greet • Each character in a String is of type char. • To get the character at a specified position in a String, use the method charAt(): • char firstChar = greet.charAt(0); // firstChar is ‘s’ • char secondChar = greet.charAt(1); // secondChar is ‘o’

  11. String Methods Some useful String methods:

  12. Calling String Methods: Some Examples • Substrings • String artist = “Pink Floyd”; • String first = artist.substring(0, 4); // first refers to “Pink” • String last = artist.substring(5); // last refers to “Floyd” • String Length • String hey = “hello!!”; • int len = hey.length(); // len is 7 • Grab a character • char first = hey.charAt(0); // first is ‘h’ • char last = hey.charAt(6); // last is ‘!’

  13. String Conversion • Convert to uppercase or lowercase • String greeting = “Hello World!”; • String lowGreet = greeting.toLowerCase(); // “hello world!” • String upGreet = greeting.toUpperCase(); // “HELLO WORLD!” • Remove leading and trailing whitespace • String big = new String(“ hello “); • String little = big.trim(); // “hello” • Replace one character with another • String hey = “hello there”; • String hey2 = hey.replace(‘e’, ‘u’); // ”hullo thuru”

  14. More String Method Calls • Finding Substrings • String myString = “hello world hello!”; • int find = myString.indexOf(“hello”); // find is 0 • int find2 = myString.lastIndexOf(“hello”); // find2 is 12 • int find3 = myString.indexOf(“hello”, 2); // find3 is 12 • Converting Numeric Values to Strings • The valueOf() method is static - we call is by prefixing the method name with the class name, String. • double x = 16.533; • String xStr = String.valueOf(x); // xStr refers to “16.533”

  15. Scanner: Reading User Input • Create a Scanner object to read console input: • Scanner console = new Scanner(System.in); • To use Scanner, you must include this import statement at the beginning of your program: • import java.util.*; • Think of the object System.in as a data source, associated with the keyboard.

  16. Tokens • The user’s input is a sequence of tokens, separated by whitespace (blank spaces, tabs, new lines). • Example: If the user types: hello 2.7 11 8 22.1 • There are 6 tokens. The Scanner object positions its cursor at the beginning of the user input. Each time a token is read, the cursor advances to the next token. Tokens are read by calling Scanner methods (next(), nextLine(), nextInt(), nextDouble()). • String x = console.next(); // “hello” • double y = console.nextDouble(); // 2.7 • int z = console.nextInt(); // 11 • double t = console.nextDouble(); // 8.0 (could have used nextInt() • String r = console.next(); // “22.1” (could have used nextDouble())

  17. Scanner Example • Write Java code that reads 5 integers from the user and prints their sum. Scanner reader = new Scanner(System.in); System.out.print(“Please enter 5 integers: “); // prompt the user // cumulative sum variable must be created and initialized to // 0 outside the loop int sum = 0; // as we read each number, we’ll add it to sum for(int i = 1; i <= 5; i++) { int num = reader.nextInt(); sum += num; } System.out.println(“Sum is “ + sum);

  18. Scanner Exercises • Write a program that asks the user how many integers they want to enter, and then computes and prints the average of the entered numbers. • Write a program that reads a line of text from the user, and prints: • the line converted to uppercase • the string with all e’s replaced with a’s • the part of the string from index 3 on • the length of the string • the original string with the string “ and all that jazz” added to the end

  19. Random Objects • Sometimes you want numbers that are, or are nearly, random. • game program simulating roll of a die or shuffling a deck of cards • Random - in package java.util - implements a random number generator • Construct a Random object, and use these methods: • nextInt(): returns a random integer • nextInt(n): returns a random integer in the interval [0, n) • nextDouble(): returns a random floating-point number in the interval [0, 1) • Example: Random generator = new Random(); int ran = generator.nextInt(6); // ran is a random # between 0 & 5 int randomDiceThrow = ran + 1; // random throw, 6 sided dice

  20. Exercise • Write a program that prints: • a random integer • a random integer from 0 to 9 • a random integer from 1 to 10 • a random floating-point number in the interval [0, 1)

  21. Objects as Parameters • Recall: When a method has a primitive type parameter, changes made to the parameter inside the method have no effect on variables in the calling method. public static void main(String[] args) { int x = 3; strange(x); // the value 3 is copied to strange() method’s parameter System.out.println(x); } public static void strange(int x) { x = 17; // parameter’s value set to 17 (variable x in main unchanged) }

  22. Objects as Parameters • A reference type variable stores the address of an object, not the object itself. So when an object is passed to a method, the address of the object is assigned to the method’s parameter. So the method can change the object. public static void main(String[] args) { Point q = new Point(0, 0); System.out.println(q.toString()); // print q’s coords strange(q); System.out.println(q.toString()); } public static void strange(Point p) { System.out.println(p.toString()); p.move(1, 2); // change to point (1, 2) } q (0, 0) p

  23. Output java.awt.Point[x=0, y=0] java.awt.Point[x=0, y=0] java.awt.Point[x=1, y=2]

More Related