SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Programmazione 2 (PR2)

Maurizio ATZORI
Dipartimento di Matematica ed Informatica
Università di Cagliari
http:/riemann.unica.it/~atzori/
Lezione 3: Costruire un oggetto
Initialization
  In “C”-style programming, structures were
  glued-together primitive types, and
  functions were separate.
  If a structure needed initialization, the
  programmer had to remember to do it.
  We often forgot…
  Just as bad, we also forgot to “clean up”
What Needs to be Initialized?
  A stream for file reading needs to be attached
  to the file.
  An array of Vectors needs to have the Vectors
  created (and themselves initialized).
  A Checkbox needs to have its state set, and
  perhaps be associated with an ActionListener.
  A Socket needs to have its IP address set.
  A Rectangle needs to have its dimensions and
  location set.
  TelefonoCellulare (inizialmente spento)
What If We Forget?
 Things don’t act the way we expect them
 to!
 We only learn about problems at runtime.
 Maybe we don’t find out until it’s too late.
 Common culprits:
   references that lead nowhere
   garbage values
How Does Java Help?
 Java initializes all class member variables
 to zero whenever we create an object.
 Java allows us to write constructors,
 special methods, one of which will be
 called on object creation.
 Java refuses to create an object (compile
 error) if we haven’t provided the right kind
 of constructor.
Constructors
 A constructor method has the same name as
 the class. It has no return type.
 There can be many different constructors, each
 with a distinct argument signature.
 (This implies that overloaded methods are OK
 in Java.)
 You specify the particular constructor you want
 when you create an object.
Example Constructor
    class Book {
       String title;
       String author;
       int numPages;
       Book() { }            // default constructor
       Book(String t, String a, int p) {
          title = t;
               author = a;
               numPages = p;
           }
         }
Making Books
 Book uselessBook = new Book();
   title is an empty character sequence
   author is an empty character sequence
   numPages is 0
 Book usefulBook = new Book(“The
   TeXBook”, “Donald Knuth”, 483);
Method Overloading
 Methods with the same name, but different sets
 of arguments.
 A natural idea (carWash the car? shirtWash the
 shirt? dogWash the dog? Nah…)
 Constructors can be overloaded; so can any
 function.
 This is OK, but not recommended:
   void print(String s, int i)
   void print(int i, String s)
 You can’t overload on the return type alone.
Overloading With Primitives
 The compiler tries to find an exact match,
 but will promote (“widen”) a value if
 necessary.
     void doSomething(long l) { // whatever }
     :
     int i = 13;
     doSomething(i);
 The compiler won’t narrow without an
 explicit cast.
The Default Constructor
 “But, how come I didn’t have to write
 constructors for the last homework?”
 The compiler will write one for you!
 But only if you haven’t written any
 constructors at all (for this class).
 A default constructor has no arguments
 (but still has the same name as the
 class).
A Common Error
     class Book {
        String title; String author; int numPages;
        Book(String t, String a, int n) {
          title = t; author = a, numPages = n;
        }
     }
     :
     Book b = new Book();
 The compiler gives an error.
 Normally, you always provide a default
 constructor that does as much as possible (but
 not too much!).
The this Keyword
 A common “C” idiom:
 MusicFile f = new MusicFile(“Yardbirds”)
 play(&f, 4);    // play the 4th track
 In object-oriented style, we want to “send a
 message” to an object, so in Java we say
 f.play(4);
 The compiler knows which object (f in this case)
 the method is being called for.
 The compiler sends this information to the
 method, in the form of a reference to f.
The this Keyword (cont.)
  If necessary, we can get a reference to the
  “current” object; it’s called this.
   public class Leaf {
     int i = 0;
     Leaf increment() {
        i++;
        return this;
     }
     void print() { System.out.println(“i = ” + i); }
     public static void main(String[] args) {
        Leaf x = new Leaf();
        x.increment().increment().increment().print();
     }
   }
Other Uses of this
  public class Flower {
     int petalCount = 0;
     String s = new String(“null”);
     Flower(int petals) { petalCount = petals; }
     Flower(String ss) { s = ss; }
     Flower(String s, int petals) {
        this(petals);
  //! this(s);                   // can’t do it twice
        this.s = s;
     }
     Flower() { this(“hi”, 47); }        // default constructor
  }
So, What Is A static Method?
 It’s a method that belongs to the class but
 not to any instance.
 It’s a method “with no this”.
 You can’t call non-static methods from
 within a static method.
 You can call a static method without
 knowing any object of the class.
Cleanup
 Java has a garbage collector that
 reclaims memory.
 If an object “can’t be reached” by a chain
 of references from a reference on the
 stack (or static storage), it is garbage.
 There is no guarantee that such an object
 will be garbage collected.
 Garbage collection is not like destruction
 (in the C++ sense).
Member Initialization
  Unitialized variables are a common
  source of bugs.
    Using an unititialized variable in method gets
    a compiler error.
    Primitive data members in classes
    automatically get initialized to “zero”.
  Is the initialized value (zero) any better
  than a “garbage value”?
Member Initialization (cont.)
  You can initialize in a class definition:
      class Notebook {
         long ram = 1048576;
         String name = new String(“IBM”);
         float price = 1995.00;
         Battery bat = new Battery();
         Disk d; // a null reference
         int i = f();
         :
      }
  This is very surprising to C++ programmers!
Constructors Again
   You can have both class initialization and constructor
   initialization:
  class Counter {
      int i = 1;
      Counter() { i = 7; }
      Counter(int j) { };
      :
   The order of initialization follows the order of the
   initialization statements in the class definition.
   It’s done before any constructor initialization, so it may
   be done twice (as Counter illustrates).
Static Member Initialization
  Same story; primitives get zero unless
  initialized, references get null unless
  initialized.
  Static initialized either
    when the first object of the type is created, or
    at the time of the first use of the variable.
  If you never use it, it’s never initialized.
Add toString() to Class A
    class A {
       int i;
       public String toString() {
         return new String("" + i);
         // or this:
         // return “” + i;
         // but not this:
         // return i;
       }
    }
Example of a Simple Time Class
public class Time {
  int hour;
  int minute;
  int second;

  Time() { setTime(0, 0, 0); }
  Time(int h) { setTime(h, 0, 0); }
  Time(int h, int m) { setTime(h, m, 0); }
  Time(int h, int m, int s) { setTime(h, m, s); }
Time Class (cont.)
  Time setTime(int h, int m, int s) {
    setHour(h);
    setMinute(m);
    setSecond(s);
    return this;
  }

  Time setHour(int h) {
    hour = (( h >= 0 && h < 24 ) ? h : 0 );
    return this;
  }
Time Class (cont.)
  Time setMinute(int m) {
    minute = (( m >= 0 && m < 60 ) ? m : 0 );
    return this;
  }
  Time setSecond(int s) {
    second = ((s >= 0 && s < 24 ) ? s : 0 );
    return this;
  }

  int getHour() { return hour; }
  int getMinute() { return minute; }
  int getSecond() { return second; }
Time Class (cont.)
    public String toString() {
      return (“” + ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) +
        ":" + ( minute < 10 ? "0" : "" ) + minute +
        ":" + ( second < 10 ? "0" : "" ) + second +
        ( hour < 12 ? " AM" : " PM" ) ;
    }
}
Time Class Driver
 public class TestTime {
   public static void main(String[] args) {
       Time t1 = new Time();
       Time t2 = new Time(20, 3, 45);

         t1.setHour(7).setMinute(32).setSecond(23);
          System.out.println("t1 is " + t1);
          System.out.println("t2 is " + t2);
     }
 }
Miscellaneous Topics: Recursion
 Joan Rivers says “I hate cleaning my house.
 Before I’m even finished I have to do it again!”

 // Joan Rivers’ algorithm (pseudo-code)
 cleanTheHouse() {
     static String message = “I’m ”
     message = message + “so ”
     shout(message + “tired of this!”)
     cleanTheHouse()
 }
Recursion
 A method that calls itself.
 At each call, new local variables are created.
 There must be a stopping condition! Joan
 doesn’t have one…
 Often a natural way to express a problem.
 Iteration might be better, because of the
 overhead of function calls and extra storage.
 It’s not always easy to convert recursion into
 iteration.
Recursion (cont.)
  Factorials are easy: n! = n(n-1)(n-2) ⋅ ⋅ ⋅ 1
  long factorial( long number) {
    if (number <= 1) // base case
        return 1;
    else
        return number * factorial(number - 1);
  }
Deitel & Deitel’s Illustration
  5!        Recursive    5!
            calls                 5! = 5*24 = 120 returned
  5 * 4!                 5 * 4!
                                       4! = 4*6 = 24 returned
       4 * 3!                 4 * 3!
                                           3! = 3*2 = 6 returned
           3 * 2!                 3 * 2!
                                                2! = 2*1=2 returned
                2 * 1!                 2 * 1!
                          Recursive             1 returned
                    1     returns          1
Variable-Length Argument Lists
  class A { int i; }
  public class VarArgs {
     static void f(Object[] x) {
        for (int i = 0; i < x.length; i++)
           System.out.println(x[i]);
     }
     public static void main(String[] args) {
         f(new Object[] {
           new Integer(47), new VarArgs(),
           new Float(3.14), new Double(11.11) } );
        f(new Object[] {"one", "two", "three" }) ;
        f(new Object[] {new A(), new A(), new A() } );
     }
  }
Variable-Length Argument Lists
 This prints
 47
 VarArgs@fee6172e
 3.14
 11.11
 one
 two
 three
 A@fee61874
 A@fee61873
 A@fee6186a

Contenu connexe

Tendances

Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionNandan Sawant
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 

Tendances (19)

Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Java practical
Java practicalJava practical
Java practical
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 

En vedette

C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式1138177709
 
C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式1138177709
 
Au Psy492 M7 A3 E Portf Dashchi C
Au Psy492 M7 A3 E Portf Dashchi CAu Psy492 M7 A3 E Portf Dashchi C
Au Psy492 M7 A3 E Portf Dashchi Ccdash72
 

En vedette (8)

Lezione01
Lezione01Lezione01
Lezione01
 
Lezione02
Lezione02Lezione02
Lezione02
 
C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式
 
C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式C 02 c语言的基本数据类型与表达式
C 02 c语言的基本数据类型与表达式
 
Au Psy492 M7 A3 E Portf Dashchi C
Au Psy492 M7 A3 E Portf Dashchi CAu Psy492 M7 A3 E Portf Dashchi C
Au Psy492 M7 A3 E Portf Dashchi C
 
Lezione01
Lezione01Lezione01
Lezione01
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione02
Lezione02Lezione02
Lezione02
 

Similaire à Lezione03

C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already KnowKevlin Henney
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 

Similaire à Lezione03 (20)

Thread
ThreadThread
Thread
 
Collections
CollectionsCollections
Collections
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Core C#
Core C#Core C#
Core C#
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Java generics
Java genericsJava generics
Java generics
 
Python tour
Python tourPython tour
Python tour
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 

Lezione03

  • 1. Programmazione 2 (PR2) Maurizio ATZORI Dipartimento di Matematica ed Informatica Università di Cagliari http:/riemann.unica.it/~atzori/ Lezione 3: Costruire un oggetto
  • 2. Initialization In “C”-style programming, structures were glued-together primitive types, and functions were separate. If a structure needed initialization, the programmer had to remember to do it. We often forgot… Just as bad, we also forgot to “clean up”
  • 3. What Needs to be Initialized? A stream for file reading needs to be attached to the file. An array of Vectors needs to have the Vectors created (and themselves initialized). A Checkbox needs to have its state set, and perhaps be associated with an ActionListener. A Socket needs to have its IP address set. A Rectangle needs to have its dimensions and location set. TelefonoCellulare (inizialmente spento)
  • 4. What If We Forget? Things don’t act the way we expect them to! We only learn about problems at runtime. Maybe we don’t find out until it’s too late. Common culprits: references that lead nowhere garbage values
  • 5. How Does Java Help? Java initializes all class member variables to zero whenever we create an object. Java allows us to write constructors, special methods, one of which will be called on object creation. Java refuses to create an object (compile error) if we haven’t provided the right kind of constructor.
  • 6. Constructors A constructor method has the same name as the class. It has no return type. There can be many different constructors, each with a distinct argument signature. (This implies that overloaded methods are OK in Java.) You specify the particular constructor you want when you create an object.
  • 7. Example Constructor class Book { String title; String author; int numPages; Book() { } // default constructor Book(String t, String a, int p) { title = t; author = a; numPages = p; } }
  • 8. Making Books Book uselessBook = new Book(); title is an empty character sequence author is an empty character sequence numPages is 0 Book usefulBook = new Book(“The TeXBook”, “Donald Knuth”, 483);
  • 9. Method Overloading Methods with the same name, but different sets of arguments. A natural idea (carWash the car? shirtWash the shirt? dogWash the dog? Nah…) Constructors can be overloaded; so can any function. This is OK, but not recommended: void print(String s, int i) void print(int i, String s) You can’t overload on the return type alone.
  • 10. Overloading With Primitives The compiler tries to find an exact match, but will promote (“widen”) a value if necessary. void doSomething(long l) { // whatever } : int i = 13; doSomething(i); The compiler won’t narrow without an explicit cast.
  • 11. The Default Constructor “But, how come I didn’t have to write constructors for the last homework?” The compiler will write one for you! But only if you haven’t written any constructors at all (for this class). A default constructor has no arguments (but still has the same name as the class).
  • 12. A Common Error class Book { String title; String author; int numPages; Book(String t, String a, int n) { title = t; author = a, numPages = n; } } : Book b = new Book(); The compiler gives an error. Normally, you always provide a default constructor that does as much as possible (but not too much!).
  • 13. The this Keyword A common “C” idiom: MusicFile f = new MusicFile(“Yardbirds”) play(&f, 4); // play the 4th track In object-oriented style, we want to “send a message” to an object, so in Java we say f.play(4); The compiler knows which object (f in this case) the method is being called for. The compiler sends this information to the method, in the form of a reference to f.
  • 14. The this Keyword (cont.) If necessary, we can get a reference to the “current” object; it’s called this. public class Leaf { int i = 0; Leaf increment() { i++; return this; } void print() { System.out.println(“i = ” + i); } public static void main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment().print(); } }
  • 15. Other Uses of this public class Flower { int petalCount = 0; String s = new String(“null”); Flower(int petals) { petalCount = petals; } Flower(String ss) { s = ss; } Flower(String s, int petals) { this(petals); //! this(s); // can’t do it twice this.s = s; } Flower() { this(“hi”, 47); } // default constructor }
  • 16. So, What Is A static Method? It’s a method that belongs to the class but not to any instance. It’s a method “with no this”. You can’t call non-static methods from within a static method. You can call a static method without knowing any object of the class.
  • 17. Cleanup Java has a garbage collector that reclaims memory. If an object “can’t be reached” by a chain of references from a reference on the stack (or static storage), it is garbage. There is no guarantee that such an object will be garbage collected. Garbage collection is not like destruction (in the C++ sense).
  • 18. Member Initialization Unitialized variables are a common source of bugs. Using an unititialized variable in method gets a compiler error. Primitive data members in classes automatically get initialized to “zero”. Is the initialized value (zero) any better than a “garbage value”?
  • 19. Member Initialization (cont.) You can initialize in a class definition: class Notebook { long ram = 1048576; String name = new String(“IBM”); float price = 1995.00; Battery bat = new Battery(); Disk d; // a null reference int i = f(); : } This is very surprising to C++ programmers!
  • 20. Constructors Again You can have both class initialization and constructor initialization: class Counter { int i = 1; Counter() { i = 7; } Counter(int j) { }; : The order of initialization follows the order of the initialization statements in the class definition. It’s done before any constructor initialization, so it may be done twice (as Counter illustrates).
  • 21. Static Member Initialization Same story; primitives get zero unless initialized, references get null unless initialized. Static initialized either when the first object of the type is created, or at the time of the first use of the variable. If you never use it, it’s never initialized.
  • 22. Add toString() to Class A class A { int i; public String toString() { return new String("" + i); // or this: // return “” + i; // but not this: // return i; } }
  • 23. Example of a Simple Time Class public class Time { int hour; int minute; int second; Time() { setTime(0, 0, 0); } Time(int h) { setTime(h, 0, 0); } Time(int h, int m) { setTime(h, m, 0); } Time(int h, int m, int s) { setTime(h, m, s); }
  • 24. Time Class (cont.) Time setTime(int h, int m, int s) { setHour(h); setMinute(m); setSecond(s); return this; } Time setHour(int h) { hour = (( h >= 0 && h < 24 ) ? h : 0 ); return this; }
  • 25. Time Class (cont.) Time setMinute(int m) { minute = (( m >= 0 && m < 60 ) ? m : 0 ); return this; } Time setSecond(int s) { second = ((s >= 0 && s < 24 ) ? s : 0 ); return this; } int getHour() { return hour; } int getMinute() { return minute; } int getSecond() { return second; }
  • 26. Time Class (cont.) public String toString() { return (“” + ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) + ":" + ( minute < 10 ? "0" : "" ) + minute + ":" + ( second < 10 ? "0" : "" ) + second + ( hour < 12 ? " AM" : " PM" ) ; } }
  • 27. Time Class Driver public class TestTime { public static void main(String[] args) { Time t1 = new Time(); Time t2 = new Time(20, 3, 45); t1.setHour(7).setMinute(32).setSecond(23); System.out.println("t1 is " + t1); System.out.println("t2 is " + t2); } }
  • 28. Miscellaneous Topics: Recursion Joan Rivers says “I hate cleaning my house. Before I’m even finished I have to do it again!” // Joan Rivers’ algorithm (pseudo-code) cleanTheHouse() { static String message = “I’m ” message = message + “so ” shout(message + “tired of this!”) cleanTheHouse() }
  • 29. Recursion A method that calls itself. At each call, new local variables are created. There must be a stopping condition! Joan doesn’t have one… Often a natural way to express a problem. Iteration might be better, because of the overhead of function calls and extra storage. It’s not always easy to convert recursion into iteration.
  • 30. Recursion (cont.) Factorials are easy: n! = n(n-1)(n-2) ⋅ ⋅ ⋅ 1 long factorial( long number) { if (number <= 1) // base case return 1; else return number * factorial(number - 1); }
  • 31. Deitel & Deitel’s Illustration 5! Recursive 5! calls 5! = 5*24 = 120 returned 5 * 4! 5 * 4! 4! = 4*6 = 24 returned 4 * 3! 4 * 3! 3! = 3*2 = 6 returned 3 * 2! 3 * 2! 2! = 2*1=2 returned 2 * 1! 2 * 1! Recursive 1 returned 1 returns 1
  • 32. Variable-Length Argument Lists class A { int i; } public class VarArgs { static void f(Object[] x) { for (int i = 0; i < x.length; i++) System.out.println(x[i]); } public static void main(String[] args) { f(new Object[] { new Integer(47), new VarArgs(), new Float(3.14), new Double(11.11) } ); f(new Object[] {"one", "two", "three" }) ; f(new Object[] {new A(), new A(), new A() } ); } }
  • 33. Variable-Length Argument Lists This prints 47 VarArgs@fee6172e 3.14 11.11 one two three A@fee61874 A@fee61873 A@fee6186a