Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 A Sorting Example (a start for Lab 4 problem number 3)

Similar presentations


Presentation on theme: "1 A Sorting Example (a start for Lab 4 problem number 3)"— Presentation transcript:

1 1 A Sorting Example (a start for Lab 4 problem number 3)

2 2 Alphabetizing Words How do we sort a list of words into alphabetic order?  compare first letter, if different then done  otherwise, compare 2 nd letter  repeat In general, this way of ordering is called lexicographic ordering

3 3 To Start: Alphabetizing Characters This is easy… if everything is lower case  for characters char1 and char2 : char1 < char2 just in case char1 precedes char2 It is just as easy if everything is upper case String s = “MixED uP cASe”; s = s.toLowerCase(); // resulting string is “mixed up case” After converting, then alphabetize

4 4 Idea Given input strings s1 and s2 of equal length. boolean isBefore(String s1, String s2) if(s1.charAt(0)<s2.charAt(0)) return true; else if(s1.charAt(0)>s2.charAt(0)) return false; else // this means they are equal check charAt(1); ….

5 5 What About Different Lengths? To complete the solution  What happens if s1 and s2 have different lengths?  e.g. “dump” comes before “dumpster” After completing isBefore(s1,s2)  How can you use it to sort an array of strings?

6 6 Classes and Objects

7 7 Problem Solving Solving a problem involves many activities:  understand the problem  design a solution  consider alternatives and refine the solution  implement the solution  test the solution These activities are not purely linear – they overlap and interact

8 8 Problem Solving Key point: break problem into manageable pieces  e.g. submethods, recursive calls When writing software, we design separate pieces that are responsible for certain parts of the solution An object-oriented approach lends itself to this kind of decomposition  breaks problems into objects and classes

9 9 Objects Informally – bits of code that represent real objects in the world Example: an object might represent an employee at a company Each employee object handles the processing and data management for that employee

10 10 Objects An object has:  state – descriptive characteristics  behaviours – what it can do what can be done to it The state includes fixed and variable characteristics Behaviours can change the state

11 11 Objects Consider a bank account object  state includes: account balance(varies over time) account number(fixed)  behaviours include: deposit/withdrawal(change balance) opening/closing

12 12 Classes Java uses the word “class” in two different ways  collections of methods (like class libraries)  descriptions of an object type So far, we have only really worked with the first kind of class

13 13 Classes An object is defined by a class  Think of a class as a blueprint for creating objects of a certain type Multiple objects can be created from the same class  “Instances” of the class The class that contains the main method represents the whole program

14 14 Objects and Classes Bank Account A class (the concept) John’s Bank Account Balance: $5,257 An object (the realization) Bill’s Bank Account Balance: $1,245,069 Mary’s Bank Account Balance: $16,833 Multiple objects from the same class

15 15 Inheritance One class can be used to derive another via inheritance Classes can be organized into hierarchies Bank Account Account Charge Account Savings Account Checking Account

16 16 Containment Sometimes an object “contains” objects of a different type  This is not the same as inheritance For example, a class Bicycle may involve:  2 Wheel objects  1 Chain object  1 Frame object  A Bicycle itself might inherit from Vehicle  A Bicycle might belong to a Rider

17 17 Bicycle Containment A graphical “contains-a” relationaship Wheel Chain Frame

18 18 Creating Objects Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class

19 19 Creating Classes Instantiating the class with new creates an object in memory Each class has one or more special methods called “constructors”  called when the object is created  used to set initial state parameters  sometimes arguments are passed  …define our own next class…

20 20 Example: String Objects We have already seen the String class //constructor String s = new String(“example”); //String methods: char c = s.charAt(3); // c = ‘m’; String s1 = s.concat(“123”); //s==“example” & s1==“example123”

21 21 String Class Constructors String s1; //create reference… no constructor s1 = new String(); //initialize to empty string String s2 = new String(“blah blah”); // initialize from a string “blah blah” char[] chars = {‘a’,’b’,’c’}; String s3 = new String(chars); //initialize from an array of characters

22 22 A Reminder about References For primitive types: num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:

23 23 A Reminder about References For object references: name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" "Steve Wozniak"

24 24 Garbage Collection When there are no longer any references to an object, it can no longer influence the running of the program  e.g. the string “Steve Wozniak” In this case, Java automatically returns this memory to the system  This is called garbage collection

25 25 Class Variables The state of an object is given by class variables or data members  the BankAccount class may have a class variable called AccountBalance Typically these are declared private (later…) Methods can use and change these variables  getBalance()  deposit(500)

26 26 Getters and Setters The state of an object is usually manipulated with methods  Instead of accessing data members  Assures the state remains consistent  e.g. getName(); setName() Methods that read and write data members are called accessors and mutators  … or getters and setters

27 27 Using “static” Two types of methods in a class definition  code library vs. object description  How do we tell which is which? Using static to differentiate  static = code library  non- static = object method

28 28 Static Methods Won’t be copied with each new object created Can be called as functions, no names needed  x = methodName();  x = ClassName.methodName(); Need all values passed as parameters

29 29 Non-static Methods Copied into each object instance Must be called with object reference  MyClass o = new MyClass(); x = o.MethodName(); Implicitly use the object that they are part of as a parameter Used in classes that describe an object type

30 30 Enumerated Types Simple types that allow you to enumerate all possible values The values are identifiers of your own choosing Any number of values can be listed Example: enum Season = {winter, spring, summer, fall};

31 31 Enumerated Types Once an enumerated type is defined, variables of that type can be declared Season time; time = Season.fall; Only admissible identifiers are allowed

32 32 Why? Just a simple way to specify a simple type  This could easily be done with full class declarations  Could also be done with integer arrays  (internally, types are stored as integers) Can not assign numeric identifiers We really won’t use these much in class

33 33 Wrapper Classes The java.lang package contains wrapper classes that correspond to each primitive type: Primitive TypeWrapper Class byteByte shortShort intInteger longLong floatFloat doubleDouble charCharacter booleanBoolean voidVoid

34 34 Wrapper Classes The following declaration creates an Integer object which represents the integer 40 as an object Integer age = new Integer(40); An object of a wrapper class can be used in any situation where a primitive value will not suffice For example, some objects serve as containers of other objects Primitive values could not be stored in such containers, but wrapper objects could be

35 35 Wrapper Classes Wrapper classes also contain static methods that help manage the associated type For example, the Integer class contains a method to convert an integer stored in a String to an int value: num = Integer.parseInt(str); The wrapper classes often contain useful constants as well For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values

36 36 Autoboxing Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = int; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed

37 37 How To Make a Wrapper class IntValue { private int iValue; public int getValue() { return iValue; } public void setValue(int i) { iValue = I; }

38 38 How To Make a Wrapper You don’t need to do this…  Just use Integer  It is better in that it has many more methods But this code shows why these are called wrapper classes  It’s like wrapping an integer inside a package Essentially the only time we use wrapper classes is for holding primitive types


Download ppt "1 A Sorting Example (a start for Lab 4 problem number 3)"

Similar presentations


Ads by Google