SlideShare ist ein Scribd-Unternehmen logo
1 von 40
© 2012 Pearson Education, Inc. All rights reserved.

                            Chapter 9:
                A Second Look at Classes and Objects

                         Starting Out with Java:
              From Control Structures through Data Structures

                                                  Second Edition


                         by Tony Gaddis and Godfrey Muganda
Chapter Topics
 Chapter 9 discusses the following main topics:
       –    Static Class Members
       –    Passing Objects as Arguments to Methods
       –    Returning Objects from Methods
       –    The toString method
       –    Writing an equals Method
       –    Methods that Copy Objects



© 2012 Pearson Education, Inc. All rights reserved.   9-2
Chapter Topics
 Chapter 9 discusses the following main topics:
       –    Aggregation
       –    The this Reference Variable
       –    Enumerated Types
       –    Garbage Collection
       –    Focus on Object-Oriented Design: Class
            Collaboration



© 2012 Pearson Education, Inc. All rights reserved.   9-3
Review of Instance Fields and Methods
 • Each instance of a class has its own copy of instance
   variables.
       – Example:
              • The Rectangle class defines a length and a width field.
              • Each instance of the Rectangle class can have different values
                stored in its length and width fields.
 • Instance methods require that an instance of a class be
   created in order to be used.
 • Instance methods typically interact with instance fields
   or calculate values based on those fields.

© 2012 Pearson Education, Inc. All rights reserved.                              9-4
Static Class Members
 • Static fields and static methods do not belong to a
   single instance of a class.
 • To invoke a static method or use a static field, the class
   name, rather than the instance name, is used.
 • Example:

 double val = Math.sqrt(25.0);



                      Class name                      Static method

© 2012 Pearson Education, Inc. All rights reserved.                   9-5
Static Fields
 • Class fields are declared using the static keyword
   between the access specifier and the field type.
       private static int instanceCount = 0;

 • The field is initialized to 0 only once, regardless of the
   number of times the class is instantiated.
       – Primitive static fields are initialized to 0 if no initialization is
         performed.

 • Examples: Countable.java, StaticDemo.java


© 2012 Pearson Education, Inc. All rights reserved.                             9-6
Static Fields

                                        instanceCount field
                                              (static)

                                                        3




                                  Object1             Object2   Object3




© 2012 Pearson Education, Inc. All rights reserved.                       9-7
Static Methods
 • Methods can also be declared static by placing the static
   keyword between the access modifier and the return type of
   the method.
       public static double milesToKilometers(double miles)
       {…}

 • When a class contains a static method, it is not necessary to
   create an instance of the class in order to use the method.
       double kilosPerMile = Metric.milesToKilometers(1.0);

 • Examples: Metric.java, MetricDemo.java



© 2012 Pearson Education, Inc. All rights reserved.                9-8
Static Methods
 • Static methods are convenient because they may be
   called at the class level.
 • They are typically used to create utility classes, such as
   the Math class in the Java Standard Library.
 • Static methods may not communicate with instance
   fields, only static fields.




© 2012 Pearson Education, Inc. All rights reserved.             9-9
Passing Objects as Arguments
 • Objects can be passed to methods as arguments.
 • Java passes all arguments by value.
 • When an object is passed as an argument, the value of the
   reference variable is passed.
 • The value of the reference variable is an address or
   reference to the object in memory.
 • A copy of the object is not passed, just a pointer to the
   object.
 • When a method receives a reference variable as an
   argument, it is possible for the method to modify the
   contents of the object referenced by the variable.


© 2012 Pearson Education, Inc. All rights reserved.            9-10
Passing Objects as Arguments
      Examples:
         PassObject.java                              A Rectangle object
         PassObject2.java
                                                           length: 12.0
                                                            width: 5.0
 displayRectangle(box);


                                Address


        public static void displayRectangle(Rectangle r)
        {
          // Display the length and width.
          System.out.println("Length: " + r.getLength() +
                             " Width: " + r.getWidth());
        }


© 2012 Pearson Education, Inc. All rights reserved.                        9-11
Returning Objects From Methods
 • Methods are not limited to returning the primitive data
   types.
 • Methods can return references to objects as well.
 • Just as with passing arguments, a copy of the object is not
   returned, only its address.
 • See example: ReturnObject.java
 • Method return type:

                            public static BankAccount getAccount()
                            {
                                …
                                 return new BankAccount(balance);
                            }



© 2012 Pearson Education, Inc. All rights reserved.                  9-12
Returning Objects from Methods
       account = getAccount();
                                                      A BankAccount Object

                                                      balance:      3200.0



     address


                                public static BankAccount getAccount()
                                {
                                   …
                                   return new BankAccount(balance);
                                }


© 2012 Pearson Education, Inc. All rights reserved.                          9-13
The toString Method
       • The toString method of a class can be called explicitly:

              Stock xyzCompany = new Stock ("XYZ", 9.62);
              System.out.println(xyzCompany.toString());

       • However, the toString method does not have to be
         called explicitly but is called implicitly whenever you pass
         an object of the class to println or print.

            Stock xyzCompany = new Stock ("XYZ", 9.62);
            System.out.println(xyzCompany);




© 2012 Pearson Education, Inc. All rights reserved.                     9-14
The toString method
 • The toString method is also called implicitly
   whenever you concatenate an object of the class with a
   string.

 Stock xyzCompany = new Stock ("XYZ", 9.62);
 System.out.println("The stock data is:n" +
   xyzCompany);




© 2012 Pearson Education, Inc. All rights reserved.         9-15
The toString Method
 • All objects have a toString method that returns the
   class name and a hash of the memory address of the
   object.
 • We can override the default method with our own to
   print out more useful information.
 • Examples: Stock.java, StockDemo1.java




© 2012 Pearson Education, Inc. All rights reserved.      9-16
The equals Method
 • When the == operator is used with reference variables,
   the memory address of the objects are compared.
 • The contents of the objects are not compared.
 • All objects have an equals method.
 • The default operation of the equals method is to
   compare memory addresses of the objects (just like the
   == operator).




© 2012 Pearson Education, Inc. All rights reserved.         9-17
The equals Method
  • The Stock class has an equals method.
  • If we try the following:

        Stock stock1 = new Stock("GMX", 55.3);
        Stock stock2 = new Stock("GMX", 55.3);
        if (stock1 == stock2) // This is a mistake.
          System.out.println("The objects are the same.");
        else
          System.out.println("The objects are not the same.");



        only the addresses of the objects are compared.


© 2012 Pearson Education, Inc. All rights reserved.              9-18
The equals Method
 • Instead of using the == operator to compare two Stock
   objects, we should use the equals method.
   public boolean equals(Stock object2)
   {
      boolean status;

        if(symbol.equals(Object2.symbol && sharePrice == Object2.sharePrice)
           status = true;
        else
           status = false;
        return status;
   }



 • Now, objects can be compared by their contents rather than by
   their memory addresses.
 • See example: StockCompare.java

© 2012 Pearson Education, Inc. All rights reserved.                            9-19
Methods That Copy Objects
 • There are two ways to copy an object.
       – You cannot use the assignment operator to copy reference
         types

       – Reference only copy
              • This is simply copying the address of an object into another
                reference variable.

       – Deep copy (correct)
              • This involves creating a new instance of the class and copying the
                values from one object into the new object.

       – Example: ObjectCopy.java

© 2012 Pearson Education, Inc. All rights reserved.                                  9-20
Copy Constructors
 • A copy constructor accepts an existing object of the same class
   and clones it
      public Stock(Stock object 2)
      {
          symbol = object2.symbol;
          sharePrice = object2.sharePrice;
      }

      // Create a Stock object
      Stock company1 = new Stock("XYZ", 9.62);

      //Create company2, a copy of company1
      Stock company2 = new Stock(company1);



© 2012 Pearson Education, Inc. All rights reserved.                  9-21
Aggregation
 • Creating an instance of one class as a reference in
   another class is called object aggregation.
 • Aggregation creates a “has a” relationship between
   objects.
 • Examples:
       – Instructor.java, Textbook.java, Course.java,
         CourseDemo.java




© 2012 Pearson Education, Inc. All rights reserved.      9-22
Aggregation in UML Diagrams
                                                        Course

                          - courseName : String
                          - Instructor : Instructor
                          - textBook : TextBook

                          + Course(name : String, instr : Instructor, text : TextBook)
                          +   getName() : String
                          +   getInstructor() : Instructor
                          +   getTextBook() : TextBook
                          +   toString() : String




                        Instructor                                                      TextBook
  - lastName : String                                            - title : String
  - firstName : String                                           - author : String
  - officeNumber : String                                        - publisher : String

                                                             + TextBook(title : String, author : String, publisher :
  + Instructor(lname : String, fname : String,                                     String)
                     office : String)                        + TextBook(object2 : TextBook)
  +Instructor(object2 : Instructor)                          + set(title : String, author : String, publisher : String)
  +set(lname : String, fname : String,                                     : void
  office : String): void                                     + toString() : String
  + toString() : String

© 2012 Pearson Education, Inc. All rights reserved.                                                                9-23
Returning References to Private Fields
 • Avoid returning references to private data elements.
 • Returning references to private variables will allow
   any object that receives the reference to modify the
   variable.




© 2012 Pearson Education, Inc. All rights reserved.       9-24
Null References
 • A null reference is a reference variable that points to nothing.
 • If a reference is null, then no operations can be performed on it.
 • References can be tested to see if they point to null prior to
   being used.
       if(name != null)
       {
         System.out.println("Name is: "
                            + name.toUpperCase());
       }

 • Examples: FullName.java, NameTester.java



© 2012 Pearson Education, Inc. All rights reserved.                     9-25
The this Reference
 • The this reference is simply a name that an object can use to
   refer to itself.
 • The this reference can be used to overcome shadowing and
   allow a parameter to have the same name as an instance field.

       public void setFeet(int feet)
       {
         this.feet = feet;
                                     Local parameter variable feet
         //sets the this instance’s feet field
         //equal to the parameter feet.
       }


                    Shadowed instance variable

© 2012 Pearson Education, Inc. All rights reserved.                  9-26
The this Reference
  • The this reference can be used to call a constructor from
    another constructor.
        public Stock(String sym)
        {
          this(sym, 0.0);
        }
        – This constructor would allow an instance of the Stock class to be
          created using only the symbol name as a parameter.
        – It calls the constructor that takes the symbol and the price, using
          sym as the symbol argument and 0 as the price argument.
  • Elaborate constructor chaining can be created using this
    technique.
  • If this is used in a constructor, it must be the first
    statement in the constructor.

© 2012 Pearson Education, Inc. All rights reserved.                             9-27
Enumerated Types
 • Known as an enum, requires declaration and
   definition like a class
 • Syntax:
      enum typeName { one or more enum constants }

       – Definition:
       enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
                  FRIDAY, SATURDAY }

       – Declaration:
       Day WorkDay; // creates a Day enum

       – Assignment:
            Day WorkDay = Day.WEDNESDAY;


© 2012 Pearson Education, Inc. All rights reserved.               9-28
Enumerated Types
 • An enum is a specialized class Day, a specialized class
                     Each are objects of type
                                                       Day.SUNDAY

  Day workDay = Day.WEDNESDAY;                         Day.MONDAY
  The workDay variable holds the address of the
  Day.WEDNESDAY object                                 Day.TUESDAY

                                   address            Day.WEDNESDAY

                                                      Day.THURSDAY

                                                        Day.FRIDAY

                                                      Day.SATURDAY


© 2012 Pearson Education, Inc. All rights reserved.                   9-29
Enumerated Types - Methods
  • toString – returns name of calling constant
  • ordinal – returns the zero-based position of the constant in the enum. For
    example the ordinal for Day.THURSDAY is 4
  • equals – accepts an object as an argument and returns true if the
    argument is equal to the calling enum constant
  • compareTo - accepts an object as an argument and returns a negative
    integer if the calling constant’s ordinal < than the argument’s ordinal, a
    positive integer if the calling constant’s ordinal > than the argument’s
    ordinal and zero if the calling constant’s ordinal == the argument’s ordinal.
  • Examples: EnumDemo.java, CarType.java, SportsCar.java,
    SportsCarDemo.java



© 2012 Pearson Education, Inc. All rights reserved.                                 9-30
Enumerated Types - Switching
  • Java allows you to test an enum constant with a
    switch statement.

  Example: SportsCarDemo2.java




© 2012 Pearson Education, Inc. All rights reserved.   9-31
Garbage Collection
 • When objects are no longer needed they should be
   destroyed.
 • This frees up the memory that they consumed.
 • Java handles all of the memory operations for you.
 • Simply set the reference to null and Java will reclaim
   the memory.




© 2012 Pearson Education, Inc. All rights reserved.         9-32
Garbage Collection
  • The Java Virtual Machine has a process that runs in the
    background that reclaims memory from released objects.
  • The garbage collector will reclaim memory from any object
    that no longer has a valid reference pointing to it.
             BankAccount account1 = new BankAccount(500.0);
             BankAccount account2 = account1;

  • This sets account1 and account2 to point to the same
    object.




© 2012 Pearson Education, Inc. All rights reserved.             9-33
Garbage Collection
                                                      A BankAccount object

   account1                  Address                   Balance:   500.0




   account2                  Address




     Here, both account1 and account2 point to the same
     instance of the BankAccount class.

© 2012 Pearson Education, Inc. All rights reserved.                          9-34
Garbage Collection
                                                      A BankAccount object

   account1                     null                   Balance:   500.0




   account2                  Address




     However, by running the statement: account1 = null;
     only account2 will be pointing to the object.



© 2012 Pearson Education, Inc. All rights reserved.                          9-35
Garbage Collection
                                                        A BankAccount object

   account1                     null                        Balance:          500.0




                                                      Since there are no valid references to this
   account2                     null
                                                      object, it is now available for the garbage
                                                      collector to reclaim.


     If we now run the statement: account2 = null;
     neither account1 or account2 will be pointing to the object.



© 2012 Pearson Education, Inc. All rights reserved.                                                 9-36
Garbage Collection
                                                      A BankAccount object

    account1                     null                  Balance:         500.0




                                                      The garbage collector reclaims
    account2                     null
                                                      the memory the next time it runs
                                                      in the background.




© 2012 Pearson Education, Inc. All rights reserved.                                      9-37
The finalize Method
 • If a method with the signature:
              public void finalize(){…}
   is included in a class, it will run just prior to the
   garbage collector reclaiming its memory.
 • The garbage collector is a background thread that runs
   periodically.
 • It cannot be determined when the finalize method
   will actually be run.


© 2012 Pearson Education, Inc. All rights reserved.         9-38
Class Collaboration
 • Collaboration – two classes interact with each other
 • If an object is to collaborate with another object, it
   must know something about the second object’s
   methods and how to call them
 • If we design a class StockPurchase that
   collaborates with the Stock class (previously
   defined), we define it to create and manipulate a
   Stock object
 See examples: StockPurchase.java, StockTrader.java



© 2012 Pearson Education, Inc. All rights reserved.         9-39
CRC Cards
          – Class, Responsibilities and Collaborations (CRC) cards are
            useful for determining and documenting a class’s
            responsibilities
                   • The things a class is responsible for knowing
                   • The actions a class is responsible for doing
          – CRC Card Layout (Example for class Stock)

                                                         Stock
                             Know stock to purchase                 Stock class
                             Know number of shares                     None
                            Calculate cost of purchase              Stock class
                                       Etc.                      None or class name




© 2012 Pearson Education, Inc. All rights reserved.                                   9-40

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (15)

Chap4java5th
Chap4java5thChap4java5th
Chap4java5th
 
Classes and objects till 16 aug
Classes and objects till 16 augClasses and objects till 16 aug
Classes and objects till 16 aug
 
Week08
Week08Week08
Week08
 
Generics
GenericsGenerics
Generics
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Intro Uml
Intro UmlIntro Uml
Intro Uml
 
Chap2java5th
Chap2java5thChap2java5th
Chap2java5th
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Cso gaddis java_chapter5
Cso gaddis java_chapter5Cso gaddis java_chapter5
Cso gaddis java_chapter5
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java Intro to Object Oriented Programming with Java
Intro to Object Oriented Programming with Java
 

Ähnlich wie Cso gaddis java_chapter9ppt

Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects conceptkavitamittal18
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6RhettB
 
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptxCh 2 Library Classes.pptx
Ch 2 Library Classes.pptxKavitaHegde4
 
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdfCh 2 Library Classes.pdf
Ch 2 Library Classes.pdfKavitaHegde4
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
02 java basics
02 java basics02 java basics
02 java basicsbsnl007
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesDigitalDsms
 

Ähnlich wie Cso gaddis java_chapter9ppt (20)

Eo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and ObjectsEo gaddis java_chapter_06_Classes and Objects
Eo gaddis java_chapter_06_Classes and Objects
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
slides 01.ppt
slides 01.pptslides 01.ppt
slides 01.ppt
 
09slide.ppt
09slide.ppt09slide.ppt
09slide.ppt
 
09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept09slide.ppt oops classes and objects concept
09slide.ppt oops classes and objects concept
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6Cso gaddis java_chapter6
Cso gaddis java_chapter6
 
Ch 2 Library Classes.pptx
Ch 2 Library Classes.pptxCh 2 Library Classes.pptx
Ch 2 Library Classes.pptx
 
Ch 2 Library Classes.pdf
Ch 2 Library Classes.pdfCh 2 Library Classes.pdf
Ch 2 Library Classes.pdf
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
02 java basics
02 java basics02 java basics
02 java basics
 
10slide.ppt
10slide.ppt10slide.ppt
10slide.ppt
 
Java oop
Java oopJava oop
Java oop
 
Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming Basic concept of Object Oriented Programming
Basic concept of Object Oriented Programming
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
 

Mehr von mlrbrown

Cso gaddis java_chapter15
Cso gaddis java_chapter15Cso gaddis java_chapter15
Cso gaddis java_chapter15mlrbrown
 
Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14mlrbrown
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12mlrbrown
 
Cso gaddis java_chapter11
Cso gaddis java_chapter11Cso gaddis java_chapter11
Cso gaddis java_chapter11mlrbrown
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10mlrbrown
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8mlrbrown
 
Cso gaddis java_chapter7
Cso gaddis java_chapter7Cso gaddis java_chapter7
Cso gaddis java_chapter7mlrbrown
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3mlrbrown
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1mlrbrown
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16mlrbrown
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15mlrbrown
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14mlrbrown
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13mlrbrown
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12mlrbrown
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11mlrbrown
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10mlrbrown
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9mlrbrown
 
Networking Chapter 7
Networking Chapter 7Networking Chapter 7
Networking Chapter 7mlrbrown
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8mlrbrown
 
Student Orientation
Student OrientationStudent Orientation
Student Orientationmlrbrown
 

Mehr von mlrbrown (20)

Cso gaddis java_chapter15
Cso gaddis java_chapter15Cso gaddis java_chapter15
Cso gaddis java_chapter15
 
Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14
 
Cso gaddis java_chapter12
Cso gaddis java_chapter12Cso gaddis java_chapter12
Cso gaddis java_chapter12
 
Cso gaddis java_chapter11
Cso gaddis java_chapter11Cso gaddis java_chapter11
Cso gaddis java_chapter11
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
Cso gaddis java_chapter7
Cso gaddis java_chapter7Cso gaddis java_chapter7
Cso gaddis java_chapter7
 
Cso gaddis java_chapter3
Cso gaddis java_chapter3Cso gaddis java_chapter3
Cso gaddis java_chapter3
 
Cso gaddis java_chapter1
Cso gaddis java_chapter1Cso gaddis java_chapter1
Cso gaddis java_chapter1
 
Networking Chapter 16
Networking Chapter 16Networking Chapter 16
Networking Chapter 16
 
Networking Chapter 15
Networking Chapter 15Networking Chapter 15
Networking Chapter 15
 
Networking Chapter 14
Networking Chapter 14Networking Chapter 14
Networking Chapter 14
 
Networking Chapter 13
Networking Chapter 13Networking Chapter 13
Networking Chapter 13
 
Networking Chapter 12
Networking Chapter 12Networking Chapter 12
Networking Chapter 12
 
Networking Chapter 11
Networking Chapter 11Networking Chapter 11
Networking Chapter 11
 
Networking Chapter 10
Networking Chapter 10Networking Chapter 10
Networking Chapter 10
 
Networking Chapter 9
Networking Chapter 9Networking Chapter 9
Networking Chapter 9
 
Networking Chapter 7
Networking Chapter 7Networking Chapter 7
Networking Chapter 7
 
Networking Chapter 8
Networking Chapter 8Networking Chapter 8
Networking Chapter 8
 
Student Orientation
Student OrientationStudent Orientation
Student Orientation
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 

Kürzlich hochgeladen (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Cso gaddis java_chapter9ppt

  • 1. © 2012 Pearson Education, Inc. All rights reserved. Chapter 9: A Second Look at Classes and Objects Starting Out with Java: From Control Structures through Data Structures Second Edition by Tony Gaddis and Godfrey Muganda
  • 2. Chapter Topics Chapter 9 discusses the following main topics: – Static Class Members – Passing Objects as Arguments to Methods – Returning Objects from Methods – The toString method – Writing an equals Method – Methods that Copy Objects © 2012 Pearson Education, Inc. All rights reserved. 9-2
  • 3. Chapter Topics Chapter 9 discusses the following main topics: – Aggregation – The this Reference Variable – Enumerated Types – Garbage Collection – Focus on Object-Oriented Design: Class Collaboration © 2012 Pearson Education, Inc. All rights reserved. 9-3
  • 4. Review of Instance Fields and Methods • Each instance of a class has its own copy of instance variables. – Example: • The Rectangle class defines a length and a width field. • Each instance of the Rectangle class can have different values stored in its length and width fields. • Instance methods require that an instance of a class be created in order to be used. • Instance methods typically interact with instance fields or calculate values based on those fields. © 2012 Pearson Education, Inc. All rights reserved. 9-4
  • 5. Static Class Members • Static fields and static methods do not belong to a single instance of a class. • To invoke a static method or use a static field, the class name, rather than the instance name, is used. • Example: double val = Math.sqrt(25.0); Class name Static method © 2012 Pearson Education, Inc. All rights reserved. 9-5
  • 6. Static Fields • Class fields are declared using the static keyword between the access specifier and the field type. private static int instanceCount = 0; • The field is initialized to 0 only once, regardless of the number of times the class is instantiated. – Primitive static fields are initialized to 0 if no initialization is performed. • Examples: Countable.java, StaticDemo.java © 2012 Pearson Education, Inc. All rights reserved. 9-6
  • 7. Static Fields instanceCount field (static) 3 Object1 Object2 Object3 © 2012 Pearson Education, Inc. All rights reserved. 9-7
  • 8. Static Methods • Methods can also be declared static by placing the static keyword between the access modifier and the return type of the method. public static double milesToKilometers(double miles) {…} • When a class contains a static method, it is not necessary to create an instance of the class in order to use the method. double kilosPerMile = Metric.milesToKilometers(1.0); • Examples: Metric.java, MetricDemo.java © 2012 Pearson Education, Inc. All rights reserved. 9-8
  • 9. Static Methods • Static methods are convenient because they may be called at the class level. • They are typically used to create utility classes, such as the Math class in the Java Standard Library. • Static methods may not communicate with instance fields, only static fields. © 2012 Pearson Education, Inc. All rights reserved. 9-9
  • 10. Passing Objects as Arguments • Objects can be passed to methods as arguments. • Java passes all arguments by value. • When an object is passed as an argument, the value of the reference variable is passed. • The value of the reference variable is an address or reference to the object in memory. • A copy of the object is not passed, just a pointer to the object. • When a method receives a reference variable as an argument, it is possible for the method to modify the contents of the object referenced by the variable. © 2012 Pearson Education, Inc. All rights reserved. 9-10
  • 11. Passing Objects as Arguments Examples: PassObject.java A Rectangle object PassObject2.java length: 12.0 width: 5.0 displayRectangle(box); Address public static void displayRectangle(Rectangle r) { // Display the length and width. System.out.println("Length: " + r.getLength() + " Width: " + r.getWidth()); } © 2012 Pearson Education, Inc. All rights reserved. 9-11
  • 12. Returning Objects From Methods • Methods are not limited to returning the primitive data types. • Methods can return references to objects as well. • Just as with passing arguments, a copy of the object is not returned, only its address. • See example: ReturnObject.java • Method return type: public static BankAccount getAccount() { … return new BankAccount(balance); } © 2012 Pearson Education, Inc. All rights reserved. 9-12
  • 13. Returning Objects from Methods account = getAccount(); A BankAccount Object balance: 3200.0 address public static BankAccount getAccount() { … return new BankAccount(balance); } © 2012 Pearson Education, Inc. All rights reserved. 9-13
  • 14. The toString Method • The toString method of a class can be called explicitly: Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany.toString()); • However, the toString method does not have to be called explicitly but is called implicitly whenever you pass an object of the class to println or print. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println(xyzCompany); © 2012 Pearson Education, Inc. All rights reserved. 9-14
  • 15. The toString method • The toString method is also called implicitly whenever you concatenate an object of the class with a string. Stock xyzCompany = new Stock ("XYZ", 9.62); System.out.println("The stock data is:n" + xyzCompany); © 2012 Pearson Education, Inc. All rights reserved. 9-15
  • 16. The toString Method • All objects have a toString method that returns the class name and a hash of the memory address of the object. • We can override the default method with our own to print out more useful information. • Examples: Stock.java, StockDemo1.java © 2012 Pearson Education, Inc. All rights reserved. 9-16
  • 17. The equals Method • When the == operator is used with reference variables, the memory address of the objects are compared. • The contents of the objects are not compared. • All objects have an equals method. • The default operation of the equals method is to compare memory addresses of the objects (just like the == operator). © 2012 Pearson Education, Inc. All rights reserved. 9-17
  • 18. The equals Method • The Stock class has an equals method. • If we try the following: Stock stock1 = new Stock("GMX", 55.3); Stock stock2 = new Stock("GMX", 55.3); if (stock1 == stock2) // This is a mistake. System.out.println("The objects are the same."); else System.out.println("The objects are not the same."); only the addresses of the objects are compared. © 2012 Pearson Education, Inc. All rights reserved. 9-18
  • 19. The equals Method • Instead of using the == operator to compare two Stock objects, we should use the equals method. public boolean equals(Stock object2) { boolean status; if(symbol.equals(Object2.symbol && sharePrice == Object2.sharePrice) status = true; else status = false; return status; } • Now, objects can be compared by their contents rather than by their memory addresses. • See example: StockCompare.java © 2012 Pearson Education, Inc. All rights reserved. 9-19
  • 20. Methods That Copy Objects • There are two ways to copy an object. – You cannot use the assignment operator to copy reference types – Reference only copy • This is simply copying the address of an object into another reference variable. – Deep copy (correct) • This involves creating a new instance of the class and copying the values from one object into the new object. – Example: ObjectCopy.java © 2012 Pearson Education, Inc. All rights reserved. 9-20
  • 21. Copy Constructors • A copy constructor accepts an existing object of the same class and clones it public Stock(Stock object 2) { symbol = object2.symbol; sharePrice = object2.sharePrice; } // Create a Stock object Stock company1 = new Stock("XYZ", 9.62); //Create company2, a copy of company1 Stock company2 = new Stock(company1); © 2012 Pearson Education, Inc. All rights reserved. 9-21
  • 22. Aggregation • Creating an instance of one class as a reference in another class is called object aggregation. • Aggregation creates a “has a” relationship between objects. • Examples: – Instructor.java, Textbook.java, Course.java, CourseDemo.java © 2012 Pearson Education, Inc. All rights reserved. 9-22
  • 23. Aggregation in UML Diagrams Course - courseName : String - Instructor : Instructor - textBook : TextBook + Course(name : String, instr : Instructor, text : TextBook) + getName() : String + getInstructor() : Instructor + getTextBook() : TextBook + toString() : String Instructor TextBook - lastName : String - title : String - firstName : String - author : String - officeNumber : String - publisher : String + TextBook(title : String, author : String, publisher : + Instructor(lname : String, fname : String, String) office : String) + TextBook(object2 : TextBook) +Instructor(object2 : Instructor) + set(title : String, author : String, publisher : String) +set(lname : String, fname : String, : void office : String): void + toString() : String + toString() : String © 2012 Pearson Education, Inc. All rights reserved. 9-23
  • 24. Returning References to Private Fields • Avoid returning references to private data elements. • Returning references to private variables will allow any object that receives the reference to modify the variable. © 2012 Pearson Education, Inc. All rights reserved. 9-24
  • 25. Null References • A null reference is a reference variable that points to nothing. • If a reference is null, then no operations can be performed on it. • References can be tested to see if they point to null prior to being used. if(name != null) { System.out.println("Name is: " + name.toUpperCase()); } • Examples: FullName.java, NameTester.java © 2012 Pearson Education, Inc. All rights reserved. 9-25
  • 26. The this Reference • The this reference is simply a name that an object can use to refer to itself. • The this reference can be used to overcome shadowing and allow a parameter to have the same name as an instance field. public void setFeet(int feet) { this.feet = feet; Local parameter variable feet //sets the this instance’s feet field //equal to the parameter feet. } Shadowed instance variable © 2012 Pearson Education, Inc. All rights reserved. 9-26
  • 27. The this Reference • The this reference can be used to call a constructor from another constructor. public Stock(String sym) { this(sym, 0.0); } – This constructor would allow an instance of the Stock class to be created using only the symbol name as a parameter. – It calls the constructor that takes the symbol and the price, using sym as the symbol argument and 0 as the price argument. • Elaborate constructor chaining can be created using this technique. • If this is used in a constructor, it must be the first statement in the constructor. © 2012 Pearson Education, Inc. All rights reserved. 9-27
  • 28. Enumerated Types • Known as an enum, requires declaration and definition like a class • Syntax: enum typeName { one or more enum constants } – Definition: enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } – Declaration: Day WorkDay; // creates a Day enum – Assignment: Day WorkDay = Day.WEDNESDAY; © 2012 Pearson Education, Inc. All rights reserved. 9-28
  • 29. Enumerated Types • An enum is a specialized class Day, a specialized class Each are objects of type Day.SUNDAY Day workDay = Day.WEDNESDAY; Day.MONDAY The workDay variable holds the address of the Day.WEDNESDAY object Day.TUESDAY address Day.WEDNESDAY Day.THURSDAY Day.FRIDAY Day.SATURDAY © 2012 Pearson Education, Inc. All rights reserved. 9-29
  • 30. Enumerated Types - Methods • toString – returns name of calling constant • ordinal – returns the zero-based position of the constant in the enum. For example the ordinal for Day.THURSDAY is 4 • equals – accepts an object as an argument and returns true if the argument is equal to the calling enum constant • compareTo - accepts an object as an argument and returns a negative integer if the calling constant’s ordinal < than the argument’s ordinal, a positive integer if the calling constant’s ordinal > than the argument’s ordinal and zero if the calling constant’s ordinal == the argument’s ordinal. • Examples: EnumDemo.java, CarType.java, SportsCar.java, SportsCarDemo.java © 2012 Pearson Education, Inc. All rights reserved. 9-30
  • 31. Enumerated Types - Switching • Java allows you to test an enum constant with a switch statement. Example: SportsCarDemo2.java © 2012 Pearson Education, Inc. All rights reserved. 9-31
  • 32. Garbage Collection • When objects are no longer needed they should be destroyed. • This frees up the memory that they consumed. • Java handles all of the memory operations for you. • Simply set the reference to null and Java will reclaim the memory. © 2012 Pearson Education, Inc. All rights reserved. 9-32
  • 33. Garbage Collection • The Java Virtual Machine has a process that runs in the background that reclaims memory from released objects. • The garbage collector will reclaim memory from any object that no longer has a valid reference pointing to it. BankAccount account1 = new BankAccount(500.0); BankAccount account2 = account1; • This sets account1 and account2 to point to the same object. © 2012 Pearson Education, Inc. All rights reserved. 9-33
  • 34. Garbage Collection A BankAccount object account1 Address Balance: 500.0 account2 Address Here, both account1 and account2 point to the same instance of the BankAccount class. © 2012 Pearson Education, Inc. All rights reserved. 9-34
  • 35. Garbage Collection A BankAccount object account1 null Balance: 500.0 account2 Address However, by running the statement: account1 = null; only account2 will be pointing to the object. © 2012 Pearson Education, Inc. All rights reserved. 9-35
  • 36. Garbage Collection A BankAccount object account1 null Balance: 500.0 Since there are no valid references to this account2 null object, it is now available for the garbage collector to reclaim. If we now run the statement: account2 = null; neither account1 or account2 will be pointing to the object. © 2012 Pearson Education, Inc. All rights reserved. 9-36
  • 37. Garbage Collection A BankAccount object account1 null Balance: 500.0 The garbage collector reclaims account2 null the memory the next time it runs in the background. © 2012 Pearson Education, Inc. All rights reserved. 9-37
  • 38. The finalize Method • If a method with the signature: public void finalize(){…} is included in a class, it will run just prior to the garbage collector reclaiming its memory. • The garbage collector is a background thread that runs periodically. • It cannot be determined when the finalize method will actually be run. © 2012 Pearson Education, Inc. All rights reserved. 9-38
  • 39. Class Collaboration • Collaboration – two classes interact with each other • If an object is to collaborate with another object, it must know something about the second object’s methods and how to call them • If we design a class StockPurchase that collaborates with the Stock class (previously defined), we define it to create and manipulate a Stock object See examples: StockPurchase.java, StockTrader.java © 2012 Pearson Education, Inc. All rights reserved. 9-39
  • 40. CRC Cards – Class, Responsibilities and Collaborations (CRC) cards are useful for determining and documenting a class’s responsibilities • The things a class is responsible for knowing • The actions a class is responsible for doing – CRC Card Layout (Example for class Stock) Stock Know stock to purchase Stock class Know number of shares None Calculate cost of purchase Stock class Etc. None or class name © 2012 Pearson Education, Inc. All rights reserved. 9-40