1 / 49

Review of Week 1

Review of Week 1. What is a Class ? What is an Object ?. What is a class ? A blue-print or a definition for a kind of object. (Exception: some classes provide only services ) What is an object ? An instance of a class -- a "thing" in a program that has: 1. behavior (methods)

hrivera
Download Presentation

Review of Week 1

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. Review of Week 1

  2. What is a Class? What is an Object? • What is a class? A blue-print or a definition for a kind of object. (Exception: some classes provide only services) • What is an object? An instance of a class -- a "thing" in a program that has: 1. behavior (methods) 2. state (attributes) 3. identity (it exists and is unique)

  3. Creating Objects • What is the statement to create a new Purse with capacity 20 coins? { Purse purse = new Purse( 20 ) ;

  4. Object versus Object Reference purse is an object reference. purse is not an object! purse = null Purse purse; // how much money in the Purse? int balance = purse.getBalance( ); NullPointerException

  5. You can Change a Reference • What amount is printed? • What happened to purse #1 Purse purse = new Purse( 20 ); // Purse #1 purse.insert( new Coin(10) ); purse = new Purse( 30 ); // Purse #2 System.out.println("You have "+ purse.getBalance( ) + " Baht");

  6. Compiling and Running Java • What is the command to compile a Java source file named "Hello.java" ? Command> javac Hello.java • What is the command to execute a Java class file named "Hello.class" ? Command> java Hello

  7. Coin - value : int <<constructor>> +Coin( value : int ) +getValue( ) : int +toString( ) : String Immutable Object Can you change a Coin object after you create it?

  8. Import What does "import java.util.Scanner" do? • include the Scanner class in compiled program. • include Scanner source code in this class • add java.util.Scanner to CLASSPATH • add java.util.Scanner to current name space

  9. Import A. The "import" command is processed by (choose one): • Java compiler • Java interpreter (Java VM) • Java program editor B. "import X.Y" is like what statement in C# ? • using X.Y; • namespace X.Y; • include "X.Y";

  10. What am I? String long Long java.lang.String "hello class" "hello class".length( ) java.lang java.lang.System System.out System.out.println("hello") java.lang.Math Math.sqrt( ) Math.PI java.lang.Comparable Object java.util.Arrays.sort(array) Identify as one of: • package • class • object • primitive type • attribute of object • instance method • static method • class constant • interface

  11. Locations • What is "java.lang" ? • Name some classes in "java.lang" • (True/False) You should always "import java.lang.*" so your program can use the classes in java.lang.

  12. 3 Packages You Should Know java.lang Core Java language classes String Object Math System java.io Input and Output classes InputStream OutputStream java.util Utility and date/time classes Scanner Date Calendar ArrayList Arrays

  13. More import (True/False) The command "import java.util.*" does... • includes the code for all classes in java.util into your program • adds all classes in java.util to the name space • makes the compiled program larger

  14. Ordering Order these statements 1, 2, 3, 4, ... __5_ private String name; // attribute __4_ public class Cat { __7_ } __1_ package packagename; __6_ public Cat(String name) { ... } __3_ /** * javadoc comment for this class * @author Your Name */ __2_ import java.util.Scanner;

  15. Ordering of Contents In Sun's Javacoding standard, what is the order of these statements (1, 2, 3, ...). __5_ public Cat(String name, Date birthday) {..} __7_ public String getName() { return name; } __6_ /** return the cat's name */ __4_ private String name; __3_ private static final char SOUND = 'meow'; __1_ import java.util.Scanner; __2_ public class Cat { attribute class constant

  16. No Ambiguity Allowed • If there are 2 or more classes with the same name in the list of imports, the compiler issues an error. • No error if you exactly specify the class name on the import command. import java.util.*; import java.sql.*; import java.util.Date; // specify the Date class public class Test { Date today = new Date( ); ...etc... } ambiguous (not clear)

  17. Constructors • What is the purpose (job) of a constructor? Initialize the state (attributes) of a new object. public Coin( int avalue ) { this.value = avalue; // initialize value of a coin } • Can you write a class with no constructors? YES - Java will automatically provide a default constructor • Can a class have more than one constructor? How?

  18. How to Write Constructor

  19. Constructors, again Can a constructor call superand call another constructor? // calling superclass constructor public Student( String name, String id, String phone ) { super( name, phone ); this.id = id; } can we do this statement first? // calling our other constructor public Student( String name, String id ) { this( name, id, "" ); } // can we do both? public Student( String name, String id ) { super( name, id ); this( name, id, "" ); }

  20. Constructors (2) • The Fraction class has multiple constructors: Fraction half = new Fraction(1, 2); // = 1/2 Fraction ten = new Fraction( 10 ); // = 10/1 • If both constructors perform similar actions, eliminate duplicate code: let one constructor invoke the other. public class Fraction { /** construct a new Fraction = num/denom */ public Fraction( long num, long denom ) { /* do the real work here */ } /** constructor makes fraction from an int. */ public Fraction( long num ) { this( numerator, 1L ); // call other constr. }

  21. Constructors (3) • What is wrong here? public class Fraction { /** construct a new Fraction object */ public Fraction( long num, long denom ) { /* do the real work here */ ... } /** constructor makes fraction from a double */ public Fraction(double x) { if ( Double.isNaN(x) ) this( 0L, 0L ); else if ( Double.isInfinite(x) ) this( 1L, 0L ); else ... }

  22. Constructor (4) • If a class has a constructor and an initialization block, which one is used when you use "new Fraction(...)" ? public class Fraction { /** initialization block */ { System.out.println("Run init block."); } /** construct a new Fraction object */ public static Fraction( long num, long denom ) { System.out.println("Run constructor..."); /* do the real work here */ } public static void main(String[] args) { Fraction half = new Fraction(1,2);

  23. The "." • What does "." mean? ...as in: System.out.println( ); Math.PI; java.util.Scanner; obj.toString( ); Answer: "." is the scope resolution operator. "obj.toString()" means "the toString() object belonging to obj". • What symbol does C++ use for Java's "." ? Answer: C++ uses :: e.g., as obj::toString();

  24. Review of Lab

  25. Coin Purse Problem A class should have just one purpose. All the class's methods are related to that purpose. Coin -value getValue( ) Purse -capacity insert( ) withdraw( ) getBalance( ) PurseUI +mainDialog( ) +insertDialog( ) +withdrawDialog( )

  26. Design of Classes Design objects (classes) to resemble things in the real world.

  27. Immutable Object • Can you change a Coin? Coin -value +Coin(value) getValue( )

  28. The Three Noble Truths of O-O Encapsulation: an object contains both data and the methods that operate on the data. It may expose some of these to the outside and hide others.This design separates the publicinterface from the implementation, and enforces data integrity. Inheritance: one class can inherit attributes and methods from another class. Polymorphism: the operation performed by a named method can depend on context. In particular, it can depend on the type of object it is applied to.

  29. Example: The Three Noble Truths • Give an example of polymorphism. Number x; // x is a reference to a Number object x = new BigDecimal( Math.PI ); // BigDecimal is a subclass of Number, so // this is OK. System.out.println("x = "+ x.toString ); // calls the toString() method of BigDecimal x = new Fraction( 2, 33 ); // Fraction is also a subclass of Number System.out.println("x = "+ x.toString ); // calls the toString() method of Fraction

  30. More Review Questions

  31. Arrays (1) • How do you declare x to reference an array of double? double [ ] x; • How do you create an array of 100 double and assign x to reference it? x = new double[100]; • How do you define an array reference y and set y to reference the same array as x? double [ ] y = x; • What is the index of the last element of x? 99 • Does the statement "y[1] = 10" change x[1]? yes. y refers to the same array as x

  32. Arrays (2) • What attribute or method returns the size of an array? length as in x.length • Is "length" an attribute or a method? attribute. In contrast, for a String s, s.length() is a method. • Using length, set "last" equal to the last element of x. double last = x[x.length - 1]; • Is x an object or primitive data type? What about x[1]? x is an object, x[1] is a double • From the questions above, what fact tells you that x must be an object, not a primitive? primitive data types don't have attributes

  33. Arrays (3) • How would create a new array z and copy x to z? double [] z = new double[x.length]; // arraycopy( src, src_start, dest, dest_start, count) System.arraycopy(x, 0, z, 0, x.length); • How would you copy x to z using a loop? for(int k=0; k<x.length; k++) z[k] = x[k]; • What does the statement "z = x" do? make z to refer to the same array as x. The old storage allocated to z is lost! • What is the meaning of this statement?String [] fruit = { "Apple", "Orange", "Grape" }; create a new array of length 3 and assign values to the array elements

  34. Arrays (4) • What is wrong with these statements?String s = "Arrays are very useful";String [] words = new String [4];words = s.split("\\s+"); //split at whitespace The "words = new String[4]" is useless! The third line will set words to a new array (returned by split), so the old array is discarded. A better way to write this is: String s = "Arrays are very useful";String [] words = s.split("\\s+");

  35. Arrays (5) • What is the value of dates[1] after this statement?Date [] dates = new Date[10]; null. This line only creates an array of Date references. It doesn't create any Date objects. • How do you create Date objectsfor this array? for(int k=0; k < dates.length; k++) dates[k] = new Date( ); • What is the value of score[1] after this statement?int [] score = new int[10]; 0"int" is a primitive data type, so the array elements contain the data values.

  36. Arrays (6) • Can you change the size of an array after you create it? For example: double [] score = new double[10];int k = 0;// read scores into an arraywhile( input.hasNextDouble() && k < score.length ) score[k++] = input.nextDouble();if ( input.hasNextDouble() ) {// oops! we need a bigger array score = new double[20]; // (1) }// now read more data... while( ... ) score[k++] = input.nextDouble(); You can't change the size of an array.Statement (1) discards the old array!

  37. Arrays (7) • How can you read data and save in an array if you don't know how much data there will be? Use an ArrayList After reading the data, convert it to an array of exactly the size of the actual data. (CJ, page 180). import java.util.ArrayList; ... ArrayList<double> arr = new ArrayList<double>( );// read scores into an arraywhile( input.hasNextDouble() ) { double ascore = input.nextDouble(); arr.add ( ascore ); }// now convert to an arraydouble [] score = new double[ arr.size() ]; score = arr.toArray( score );

  38. String, Double, Integer, ... • After creating a String object, can you change the String object? No. Strings are immutable.The String class doesn't contain any "set", "append", "insert", "clear", "delete" or other methods to modify a string object. • What about String s = "hello"; s = s + " world"; Doesn't that change the String s? No. "+" creates a new string. • Can you change the value of a Double, Integer, etc.? No. These objects are also immutable. immutable: cannot be changed.

  39. String Processing (1) • Why is this loop inefficient? String text; // text read from the input Scanner input = new Scanner(System.in); while ( input.hasNext( ) ) { String word = input.next( ); text = text + " " + word; // (1) } Each time (1) appends a word, it must copy the entire String (text) to a new string! The old String is discarded. • How could you make this more efficient?

  40. append is polymorphic String Processing (2) • How could you make this more efficient? Use a StringBuffer or StringBuilder object. You can append strings to a StringBuilder (faster) or StringBuffer (thread-safe). When you are finished, convert the object to a String! StringBuilder buf = new StringBuilder(); Scanner input = new Scanner(System.in); while ( input.hasNext( ) ) { String word = input.next( ); buf.append(' '); buf.append(word); } String text = buf.toString( );

  41. String Processing (3) • Is it worth the effort to use write extra code to use StringBuilder? See my example program: TestStringBuilder.java It reads a file word-by-word and appends each word to a String or StringBuilder, as in the previous slides. For a 40KB file from the Java tutorial, I recorded these times: read and append to a String: 6.60 seconds read and append to StringBuilder: 0.03 seconds read and append to StringBuffer: 0.03 seconds For StringBuffer and StringBuilder, these times include converting the result into a String object!

  42. Immutable Objects • What does it mean for an object to be immutable? • Does this class define immutable objects? public class Appointment { private Date date; private String description; public Appointment( Date when, String what ) { date = when; description = what; } public Date getDate( ) { return date; } public String getDescription { return description; } } No mutator methods!

  43. Immutable Objects (2) • It is mutable because Date is mutable. (See Horstmann for example.) • To fix it, always copy the mutable Date object: public class Appointment { private Date date; private String description; public Appointment( Date when, String what ) { date = (Date) when.clone(); description = what; } public Date getDate( ) { return (Date)date.clone(); } public String getDescription { return description; } }

  44. A Mutable Object • A Date object is mutable. The Date class provides methods such as setYear(int), setMonth(int), and setDate(int) to change the year, month, or day. Date millenia = new Date( 101, // = year - 1900 Calendar.JANUARY, // = month 1 ); // = day System.out.println(millenia); // prints "January 1, 2001" millenia.setYear(99); // change year to 1999 millenia.setMonth(Calendar.MARCH); millenia.setDate(15); System.out.println(millenia); // prints "March 15, 1999"

  45. Encapsulation • How can a class enforce encapsulation of attributes and still give the other classes ability to read an attribute's value? Make the attributes private and provide an accessor method • Give an example. class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for name public String getName() { return name; }

  46. Encapsulation and Mutability • A Date object is mutable. The Date class has methods such as setYear(int), setMonth(int), and setDate(int). • Does this getBirthday() method break encapsulation of the birthday object? class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for birthday public Date getBirthday() { return birthday; }

  47. Encapsulation and Mutability (2) • How would you fix this problem? For mutable objects, return a copy of the object. • Why? Give an example. Person you = new Person("aname", new Date(..) ); Date bd = you.getBirthday( ); bd.setYear( 99 ); // change the year to 1900 + 99 class Person { ... // accessor method for birthday public Date getBirthday() { return new Date( birthday ); } • For more info, see Core Java chapter 4.

  48. Encapsulation and Mutability (3) • Does this getName() method break encapsulation of the name object? class Person { private String name; private Date birthday; public Person(String name, Date birthday) { /* set the attributes */ } // accessor method for name public String getName() { return name; } • No. String objects are immutable, so the caller cannot use the return value to change the name attribute.

  49. Encapsulation and Accessor Methods • For mutable objects, an accessor should return a copy: • For primitive data types and immutable objects, it is safe for an accessor method to return the value: class BankAccount { private long balance; // account balance /** return the account balance */ public long getBalance() { return balance; // this is safe } class Person { /** return the person's birthday */ public Date getBirthday() { return new Date( birthday ); }

More Related