SlideShare una empresa de Scribd logo
1 de 44
Chapter 10 Thinking in Objects




   Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                        rights reserved.
                                                                                                  1
Motivations
You see the advantages of object-oriented programming
from the preceding two chapters. This chapter will
demonstrate how to solve problems using the object-
oriented paradigm. Before studying these examples, we
first introduce several language features for supporting
these examples.




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          2
Objectives
   To create immutable objects from immutable classes to protect the
    contents of objects (§10.2).
   To determine the scope of variables in the context of a class (§10.3).
   To use the keyword this to refer to the calling object itself (§10.4).
   To apply class abstraction to develop software (§10.5).
   To explore the differences between the procedural paradigm and object-
    oriented paradigm (§10.6).
   To develop classes for modeling composition relationships (§10.7).
   To design programs using the object-oriented paradigm (§§10.8–10.10).
   To design classes that follow the class-design guidelines (§10.11).
   To create objects for primitive values using the wrapper classes (Byte,
    Short, Integer, Long, Float, Double, Character, and Boolean) (§10.12).
   To simplify programming using automatic conversion between primitive
    types and wrapper class types (§10.13).
   To use the BigInteger and BigDecimal classes for computing very large
    numbers with arbitrary precisions (§10.14).
               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                              3
Immutable Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class. If you delete the set method in
the Circle class in the preceding example, the class would be
immutable because radius is private and cannot be changed
without a set method.

A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.


           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          4
Example                                                public class BirthDate {
                                                                         private int year;
public class Student {
                                                                         private int month;
  private int id;
  private BirthDate birthDate;                                           private int day;

    public Student(int ssn,                                                public BirthDate(int newYear,
        int year, int month, int day) {
                                                                               int newMonth, int newDay) {
      id = ssn;
      birthDate = new BirthDate(year, month, day);                           year = newYear;
    }                                                                        month = newMonth;
                                                                             day = newDay;
    public int getId() {
                                                                           }
      return id;
    }
                                                                           public void setYear(int newYear) {
    public BirthDate getBirthDate() {                                        year = newYear;
      return birthDate;
                                                                           }
    }
}                                                                      }


       public class Test {
         public static void main(String[] args) {
           Student student = new Student(111223333, 1970, 5, 3);
           BirthDate date = student.getBirthDate();
           date.setYear(2010); // Now the student birth year is changed!
         }
       }

                     Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                          rights reserved.
                                                                                                                    5
What Class is Immutable?
For a class to be immutable, it must mark all data fields private
and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          6
Scope of Variables
   The scope of instance and static variables is the
    entire class. They can be declared anywhere inside
    a class.
   The scope of a local variable starts from its
    declaration and continues to the end of the block
    that contains the variable. A local variable must be
    initialized explicitly before it can be used.


         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        7
The this Keyword
 The this keyword is the name of a reference that
 refers to an object itself. One common use of the
 this keyword is reference a class’s hidden data
 fields.
 Another common use of the this keyword to
 enable a constructor to invoke another
 constructor of the same class.


        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       8
Reference the Hidden Data Fields
public class F {                                    Suppose that f1 and f2 are two objects of F.
  private int i = 5;                                F f1 = new F(); F f2 = new F();
  private static double k = 0;
                                                    Invoking f1.setI(10) is to execute
    void setI(int i) {                                 this.i = 10, where this refers f1
      this.i = i;
    }                                               Invoking f2.setI(45) is to execute
                                                       this.i = 45, where this refers f2
    static void setK(double k) {
      F.k = k;
    }
}




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                 9
Calling Overloaded Constructor
public class Circle {
  private double radius;

    public Circle(double radius) {
      this.radius = radius;
    }                  this must be explicitly used to reference the data
                                               field radius of the object being constructed
    public Circle() {
      this(1.0);
    }                                          this is used to invoke another constructor

    public double getArea() {
      return this.radius * this.radius * Math.PI;
    }
}              Every instance variable belongs to an instance represented by this,
               which is normally omitted
               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                              10
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides
a description of the class and let the user know how the
class can be used. The user of the class does not need to
know how the class is implemented. The detail of
implementation is encapsulated and hidden from the user.


Class implementation                                             Class Contract
is like a black box                                              (Signatures of                                     Clients use the
hidden from the clients
                                          Class                public methods and                                  class through the
                                                                public constants)                                 contract of the class




                          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                               rights reserved.
                                                                                                                                   11
Designing the Loan Class
               Loan
-annualInterestRate: double           The annual interest rate of the loan (default: 2.5).
-numberOfYears: int                   The number of years for the loan (default: 1)
-loanAmount: double                   The loan amount (default: 1000).
-loanDate: Date                       The date this loan was created.

+Loan()                               Constructs a default Loan object.
+Loan(annualInterestRate: double,     Constructs a loan with specified interest rate, years, and
  numberOfYears: int,                   loan amount.
  loanAmount: double)
+getAnnualInterestRate(): double      Returns the annual interest rate of this loan.
+getNumberOfYears(): int              Returns the number of the years of this loan.
+getLoanAmount(): double              Returns the amount of this loan.
+getLoanDate(): Date                  Returns the date of the creation of this loan.
+setAnnualInterestRate(             Sets a new annual interest rate to this loan.
  annualInterestRate: double): void
+setNumberOfYears(                  Sets a new number of years to this loan.
   numberOfYears: int): void
+setLoanAmount(                       Sets a new amount to this loan.
   loanAmount: double): void
+getMonthlyPayment(): double          Returns the monthly payment of this loan.
+getTotalPayment(): double            Returns the total payment of this loan.



                                                         Loan                   TestLoanClass                             Run
                           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                                rights reserved.
                                                                                                                                12
Object-Oriented Thinking
Chapters 1-7 introduced fundamental programming
techniques for problem solving using loops, methods, and
arrays. The studies of these techniques lay a solid
foundation for object-oriented programming. Classes
provide more flexibility and modularity for building
reusable software. This section improves the solution for a
problem introduced in Chapter 3 using the object-oriented
approach. From the improvements, you will gain the
insight on the differences between the procedural
programming and object-oriented programming and see
the benefits of developing reusable code using objects and
classes.

          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         13
The BMI Class
                                                 The get methods for these data fields are
                                                 provided in the class, but omitted in the
                                                 UML diagram for brevity.
                  BMI
-name: String                                   The name of the person.
-age: int                                       The age of the person.
-weight: double                                 The weight of the person in pounds.
-height: double                                 The height of the person in inches.

+BMI(name: String, age: int, weight:            Creates a BMI object with the specified
 double, height: double)                         name, age, weight, and height.
+BMI(name: String, weight: double,              Creates a BMI object with the specified
 height: double)                                 name, weight, height, and a default age
                                                 20.
+getBMI(): double                               Returns the BMI
+getStatus(): String                            Returns the BMI status (e.g., normal,
                                                 overweight, etc.)




                                                  BMI                       UseBMIClass                                Run
                        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                             rights reserved.
                                                                                                                             14
Object Composition
Composition is actually a special case of the aggregation
relationship. Aggregation models has-a relationships and
represents an ownership relationship between two objects.
The owner object is called an aggregating object and its
class an aggregating class. The subject object is called an
aggregated object and its class an aggregated class.

                        Composition                                      Aggregation


          1                           1                                     1                      1..3
   Name                                            Student                                                Address


          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                               15
Class Representation
An aggregation relationship is usually represented as a data
field in the aggregating class. For example, the relationship
in Figure 10.6 can be represented as follows:

public class Name {                public class Student {                                     public class Address {
    ...                              private Name name;                                           ...
}                                    private Address address;                                 }

                                       ...
                                   }

    Aggregated class                         Aggregating class                                        Aggregated class




                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                     16
Aggregation or Composition
Since aggregation and composition
relationships are represented using classes in
similar ways, many texts don’t differentiate
them and call both compositions.




       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                            rights reserved.
                                                                                                      17
Aggregation Between Same Class
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.
                          1
       Person
                                             Supervisor
       1




                                    public class Person {
                                      // The type for the data is the class itself
                                      private Person supervisor;
                                      ...
                                    }
            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           18
Aggregation Between Same Class
What happens if a person has several supervisors?

                             1
       Person
                                                Supervisor
       m




                                                     public class Person {
                                                       ...
                                                       private Person[] supervisors;
                                                     }




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          19
Example: The Course Class
                Course
-name: String                                       The name of the course.
-students: String[]                                 The students who take the course.
-numberOfStudents: int                              The number of students (default: 0).
+Course(name: String)                               Creates a Course with the specified name.
+getName(): String                                  Returns the course name.
+addStudent(student: String): void Adds a new student to the course list.
+getStudents(): String[]           Returns the students for the course.
+getNumberOfStudents(): int                         Returns the number of students for the course.



                                        Course                        TestCource                               Run

                Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                     rights reserved.
                                                                                                                     20
Example: The
             StackOfIntegers Class
         StackOfIntegers
-elements: int[]                                  An array to store integers in the stack.
-size: int                                        The number of integers in the stack.
+StackOfIntegers()                                Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int)                   Constructs an empty stack with a specified capacity.
+empty(): boolean                                 Returns true if the stack is empty.
+peek(): int                                      Returns the integer at the top of the stack without
                                                    removing it from the stack.
+push(value: int): int                            Stores an integer into the top of the stack.
+pop(): int                                       Removes the integer at the top of the stack and returns it.
+getSize(): int                                   Returns the number of elements in the stack.


                      TestStackOfIntegers                                                      Run
                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                 21
Designing the StackOfIntegers Class
Data1                 Data2                               Data3

                                                                                                           Data3
                                                                              Data2                        Data2
                                         Data1                                Data1                        Data1


Data3                     Data2                                   Data1


        Data2
        Data1                                Data1




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                               22
Implementing
  StackOfIntegers Class
elements[capacity – 1]
                                  .
                                  .
                                  .
      elements[size-1]                     top
                                                                                                      capacity

                                  .
                                  .                                          size
                                  .
           elements[1]
           elements[0]                    bottom



                StackOfIntegers
       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                            rights reserved.
                                                                                                                 23
Designing the GuessDate Class
              GuessDate
-dates: int[][][]                               The static array to hold dates.

+getValue(setNo: int, row: int,                 Returns a date at the specified row and column in a given set.
  column: int): int




                         GuessDate                         UseGuessDateClass                                       Run

                    Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                         rights reserved.
                                                                                                                         24
Designing a Class
 (Coherence)   A class should describe a single
 entity, and all the class operations should logically
 fit together to support a coherent purpose. You can
 use a class for students, for example, but you
 should not combine students and staff in the same
 class, because students and staff have different
 entities.



        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       25
Designing a Class, cont.
   (Separating responsibilities) A single entity with too
    many responsibilities can be broken into several classes to
    separate responsibilities. The classes String,
    StringBuilder, and StringBuffer all deal with strings, for
    example, but have different responsibilities. The String
    class deals with immutable strings, the StringBuilder class
    is for creating mutable strings, and the StringBuffer class
    is similar to StringBuilder except that StringBuffer
    contains synchronized methods for updating strings.



            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           26
Designing a Class, cont.
 Classes are designed for reuse. Users can
 incorporate classes in many different combinations,
 orders, and environments. Therefore, you should
 design a class that imposes no restrictions on what
 or when the user can do with it, design the properties
 to ensure that the user can set properties in any
 order, with any combination of values, and design
 methods to function independently of their order of
 occurrence.

            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           27
Designing a Class, cont.
 Providea public no-arg constructor and override the
 equals method and the toString method defined in
 the Object class whenever possible.




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           28
Designing a Class, cont.
 Follow  standard Java programming style and
 naming conventions. Choose informative
 names for classes, data fields, and methods.
 Always place the data declaration before the
 constructor, and place constructors before
 methods. Always provide a constructor and
 initialize variables to avoid programming
 errors.


     Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                          rights reserved.
                                                                                                    29
Using Visibility Modifiers
   Each class can present two contracts – one for the users
    of the class and one for the extenders of the class. Make
    the fields private and accessor methods public if they are
    intended for the users of the class. Make the fields or
    method protected if they are intended for extenders of the
    class. The contract for the extenders encompasses the
    contract for the users. The extended class may increase
    the visibility of an instance method from protected to
    public, or change its implementation, but you should
    never change the implementation in a way that violates
    that contract.

              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             30
Using Visibility Modifiers, cont.
A class should use the private modifier to hide its
 data from direct access by clients. You can use get
 methods and set methods to provide users with
 access to the private data, but only to private data
 you want the user to see or to modify. A class
 should also hide methods not intended for client use.
 The gcd method in the Rational class in Example
 11.2, “The Rational Class,” is private, for example,
 because it is only for internal use within the class.

          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         31
Using the static Modifier

A  property that is shared by all the
 instances of the class should be declared
 as a static property.




       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                            rights reserved.
                                                                                                      32
Wrapper Classes
   Boolean                        Integer                               NOTE: (1) The wrapper classes do
                                                                          not have no-arg constructors. (2)
   Character                      Long                                  The instances of all wrapper
                                                                          classes are immutable, i.e., their
   Short                          Float                                 internal values cannot be changed
                                                                          once the objects are created.
   Byte                           Double




              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             33
The toString, equals, and hashCode
              Methods
Each wrapper class overrides the toString,
equals, and hashCode methods defined in the
Object class. Since all the numeric wrapper
classes and the Character class implement
the Comparable interface, the compareTo
method is implemented in these classes.


        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       34
The Integer and Double Classes
             java.lang.Integer                                                             java.lang.Double
-value: int                                                     -value: double
+MAX_VALUE: int                                                 +MAX_VALUE: double
+MIN_VALUE: int                                                 +MIN_VALUE: double


+Integer(value: int)                                            +Double(value: double)
+Integer(s: String)                                             +Double(s: String)
+byteValue(): byte                                              +byteValue(): byte
+shortValue(): short                                            +shortValue(): short
+intValue(): int                                                +intValue(): int
+longVlaue(): long                                              +longVlaue(): long
+floatValue(): float                                            +floatValue(): float
+doubleValue():double                                           +doubleValue():double
+compareTo(o: Integer): int                                     +compareTo(o: Double): int
+toString(): String                                             +toString(): String
+valueOf(s: String): Integer                                    +valueOf(s: String): Double
+valueOf(s: String, radix: int): Integer                        +valueOf(s: String, radix: int): Double
+parseInt(s: String): int                                       +parseDouble(s: String): double
+parseInt(s: String, radix: int): int                           +parseDouble(s: String, radix: int): double


                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                 35
The Integer Class
       and the Double Class
 Constructors

 Class    Constants MAX_VALUE, MIN_VALUE

 Conversion                 Methods




     Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                          rights reserved.
                                                                                                    36
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string
representing the numeric value. The constructors
for Integer and Double are:
  public Integer(int value)
  public Integer(String s)
  public Double(double value)
  public Double(String s)

          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         37
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE. MAX_VALUE
represents the maximum value of the corresponding
primitive data type. For Byte, Short, Integer, and Long,
MIN_VALUE represents the minimum byte, short, int,
and long values. For Float and Double, MIN_VALUE
represents the minimum positive float and double values.
The following statements display the maximum integer
(2,147,483,647), the minimum positive float (1.4E-45),
and the maximum double floating-point number
(1.79769313486231570e+308d).
         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        38
Conversion Methods
Each numeric wrapper class implements the
abstract methods doubleValue, floatValue,
intValue, longValue, and shortValue, which
are defined in the Number class. These
methods “convert” objects into primitive
type values.



        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       39
The Static valueOf Methods
The numeric wrapper classes have a useful
class method, valueOf(String s). This method
creates a new object initialized to the value
represented by the specified string. For
example:


  Double doubleObject = Double.valueOf("12.4");
  Integer integerObject = Integer.valueOf("12");

         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        40
The Methods for Parsing Strings into
            Numbers
You have used the parseInt method in the
Integer class to parse a numeric string into an
int value and the parseDouble method in the
Double class to parse a numeric string into a
double value. Each numeric wrapper class
has two overloaded parsing methods to parse
a numeric string into an appropriate numeric
value.
        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       41
Automatic Conversion Between Primitive
               Types and Wrapper Class Types

JDK 1.5 allows primitive type and wrapper classes to be converted automatically.
For example, the following statement in (a) can be simplified as in (b):


Integer[] intArray = {new Integer(2),                        Equivalent
                                                                               Integer[] intArray = {2, 4, 3};
  new Integer(4), new Integer(3)};

                  (a)                                          New JDK 1.5 boxing                             (b)




Integer[] intArray = {1, 2, 3};
System.out.println(intArray[0] + intArray[1] + intArray[2]);


                        Unboxing



               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                                    42
BigInteger and BigDecimal
If you need to compute with very large integers or
high precision floating-point values, you can use
the BigInteger and BigDecimal classes in the
java.math package. Both are immutable. Both
extend the Number class and implement the
Comparable interface.




        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       43
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);

                                                          LargeFactorial                                 Run

BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                               44

Más contenido relacionado

La actualidad más candente

La actualidad más candente (7)

Lecture19
Lecture19Lecture19
Lecture19
 
Lecture21
Lecture21Lecture21
Lecture21
 
Lecture07
Lecture07Lecture07
Lecture07
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
03slide
03slide03slide
03slide
 
Dacj 1-2 a
Dacj 1-2 aDacj 1-2 a
Dacj 1-2 a
 
Javabeanproperties
JavabeanpropertiesJavabeanproperties
Javabeanproperties
 

Similar a JavaYDL10 (20)

10slide.ppt
10slide.ppt10slide.ppt
10slide.ppt
 
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
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objects
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
Cso gaddis java_chapter9ppt
Cso gaddis java_chapter9pptCso gaddis java_chapter9ppt
Cso gaddis java_chapter9ppt
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
JavaYDL8
JavaYDL8JavaYDL8
JavaYDL8
 
Java beans
Java beansJava beans
Java beans
 
Oops
OopsOops
Oops
 
oop Lecture 10
oop Lecture 10oop Lecture 10
oop Lecture 10
 
Ch2
Ch2Ch2
Ch2
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"Java™ (OOP) - Chapter 8: "Objects and Classes"
Java™ (OOP) - Chapter 8: "Objects and Classes"
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Oop java
Oop javaOop java
Oop java
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 

Más de Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 

Más de Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 

Último (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 

JavaYDL10

  • 1. Chapter 10 Thinking in Objects Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1
  • 2. Motivations You see the advantages of object-oriented programming from the preceding two chapters. This chapter will demonstrate how to solve problems using the object- oriented paradigm. Before studying these examples, we first introduce several language features for supporting these examples. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2
  • 3. Objectives  To create immutable objects from immutable classes to protect the contents of objects (§10.2).  To determine the scope of variables in the context of a class (§10.3).  To use the keyword this to refer to the calling object itself (§10.4).  To apply class abstraction to develop software (§10.5).  To explore the differences between the procedural paradigm and object- oriented paradigm (§10.6).  To develop classes for modeling composition relationships (§10.7).  To design programs using the object-oriented paradigm (§§10.8–10.10).  To design classes that follow the class-design guidelines (§10.11).  To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§10.12).  To simplify programming using automatic conversion between primitive types and wrapper class types (§10.13).  To use the BigInteger and BigDecimal classes for computing very large numbers with arbitrary precisions (§10.14). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3
  • 4. Immutable Objects and Classes If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class. If you delete the set method in the Circle class in the preceding example, the class would be immutable because radius is private and cannot be changed without a set method. A class with all private data fields and without mutators is not necessarily immutable. For example, the following class Student has all private data fields and no mutators, but it is mutable. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4
  • 5. Example public class BirthDate { private int year; public class Student { private int month; private int id; private BirthDate birthDate; private int day; public Student(int ssn, public BirthDate(int newYear, int year, int month, int day) { int newMonth, int newDay) { id = ssn; birthDate = new BirthDate(year, month, day); year = newYear; } month = newMonth; day = newDay; public int getId() { } return id; } public void setYear(int newYear) { public BirthDate getBirthDate() { year = newYear; return birthDate; } } } } public class Test { public static void main(String[] args) { Student student = new Student(111223333, 1970, 5, 3); BirthDate date = student.getBirthDate(); date.setYear(2010); // Now the student birth year is changed! } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5
  • 6. What Class is Immutable? For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6
  • 7. Scope of Variables  The scope of instance and static variables is the entire class. They can be declared anywhere inside a class.  The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be initialized explicitly before it can be used. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7
  • 8. The this Keyword  The this keyword is the name of a reference that refers to an object itself. One common use of the this keyword is reference a class’s hidden data fields.  Another common use of the this keyword to enable a constructor to invoke another constructor of the same class. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8
  • 9. Reference the Hidden Data Fields public class F { Suppose that f1 and f2 are two objects of F. private int i = 5; F f1 = new F(); F f2 = new F(); private static double k = 0; Invoking f1.setI(10) is to execute void setI(int i) { this.i = 10, where this refers f1 this.i = i; } Invoking f2.setI(45) is to execute this.i = 45, where this refers f2 static void setK(double k) { F.k = k; } } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9
  • 10. Calling Overloaded Constructor public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } this must be explicitly used to reference the data field radius of the object being constructed public Circle() { this(1.0); } this is used to invoke another constructor public double getArea() { return this.radius * this.radius * Math.PI; } } Every instance variable belongs to an instance represented by this, which is normally omitted Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10
  • 11. Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. Class implementation Class Contract is like a black box (Signatures of Clients use the hidden from the clients Class public methods and class through the public constants) contract of the class Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11
  • 12. Designing the Loan Class Loan -annualInterestRate: double The annual interest rate of the loan (default: 2.5). -numberOfYears: int The number of years for the loan (default: 1) -loanAmount: double The loan amount (default: 1000). -loanDate: Date The date this loan was created. +Loan() Constructs a default Loan object. +Loan(annualInterestRate: double, Constructs a loan with specified interest rate, years, and numberOfYears: int, loan amount. loanAmount: double) +getAnnualInterestRate(): double Returns the annual interest rate of this loan. +getNumberOfYears(): int Returns the number of the years of this loan. +getLoanAmount(): double Returns the amount of this loan. +getLoanDate(): Date Returns the date of the creation of this loan. +setAnnualInterestRate( Sets a new annual interest rate to this loan. annualInterestRate: double): void +setNumberOfYears( Sets a new number of years to this loan. numberOfYears: int): void +setLoanAmount( Sets a new amount to this loan. loanAmount: double): void +getMonthlyPayment(): double Returns the monthly payment of this loan. +getTotalPayment(): double Returns the total payment of this loan. Loan TestLoanClass Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12
  • 13. Object-Oriented Thinking Chapters 1-7 introduced fundamental programming techniques for problem solving using loops, methods, and arrays. The studies of these techniques lay a solid foundation for object-oriented programming. Classes provide more flexibility and modularity for building reusable software. This section improves the solution for a problem introduced in Chapter 3 using the object-oriented approach. From the improvements, you will gain the insight on the differences between the procedural programming and object-oriented programming and see the benefits of developing reusable code using objects and classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13
  • 14. The BMI Class The get methods for these data fields are provided in the class, but omitted in the UML diagram for brevity. BMI -name: String The name of the person. -age: int The age of the person. -weight: double The weight of the person in pounds. -height: double The height of the person in inches. +BMI(name: String, age: int, weight: Creates a BMI object with the specified double, height: double) name, age, weight, and height. +BMI(name: String, weight: double, Creates a BMI object with the specified height: double) name, weight, height, and a default age 20. +getBMI(): double Returns the BMI +getStatus(): String Returns the BMI status (e.g., normal, overweight, etc.) BMI UseBMIClass Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14
  • 15. Object Composition Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects. The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class. Composition Aggregation 1 1 1 1..3 Name Student Address Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15
  • 16. Class Representation An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationship in Figure 10.6 can be represented as follows: public class Name { public class Student { public class Address { ... private Name name; ... } private Address address; } ... } Aggregated class Aggregating class Aggregated class Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16
  • 17. Aggregation or Composition Since aggregation and composition relationships are represented using classes in similar ways, many texts don’t differentiate them and call both compositions. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17
  • 18. Aggregation Between Same Class Aggregation may exist between objects of the same class. For example, a person may have a supervisor. 1 Person Supervisor 1 public class Person { // The type for the data is the class itself private Person supervisor; ... } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18
  • 19. Aggregation Between Same Class What happens if a person has several supervisors? 1 Person Supervisor m public class Person { ... private Person[] supervisors; } Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19
  • 20. Example: The Course Class Course -name: String The name of the course. -students: String[] The students who take the course. -numberOfStudents: int The number of students (default: 0). +Course(name: String) Creates a Course with the specified name. +getName(): String Returns the course name. +addStudent(student: String): void Adds a new student to the course list. +getStudents(): String[] Returns the students for the course. +getNumberOfStudents(): int Returns the number of students for the course. Course TestCource Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20
  • 21. Example: The StackOfIntegers Class StackOfIntegers -elements: int[] An array to store integers in the stack. -size: int The number of integers in the stack. +StackOfIntegers() Constructs an empty stack with a default capacity of 16. +StackOfIntegers(capacity: int) Constructs an empty stack with a specified capacity. +empty(): boolean Returns true if the stack is empty. +peek(): int Returns the integer at the top of the stack without removing it from the stack. +push(value: int): int Stores an integer into the top of the stack. +pop(): int Removes the integer at the top of the stack and returns it. +getSize(): int Returns the number of elements in the stack. TestStackOfIntegers Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21
  • 22. Designing the StackOfIntegers Class Data1 Data2 Data3 Data3 Data2 Data2 Data1 Data1 Data1 Data3 Data2 Data1 Data2 Data1 Data1 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22
  • 23. Implementing StackOfIntegers Class elements[capacity – 1] . . . elements[size-1] top capacity . . size . elements[1] elements[0] bottom StackOfIntegers Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23
  • 24. Designing the GuessDate Class GuessDate -dates: int[][][] The static array to hold dates. +getValue(setNo: int, row: int, Returns a date at the specified row and column in a given set. column: int): int GuessDate UseGuessDateClass Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24
  • 25. Designing a Class  (Coherence) A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. You can use a class for students, for example, but you should not combine students and staff in the same class, because students and staff have different entities. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25
  • 26. Designing a Class, cont.  (Separating responsibilities) A single entity with too many responsibilities can be broken into several classes to separate responsibilities. The classes String, StringBuilder, and StringBuffer all deal with strings, for example, but have different responsibilities. The String class deals with immutable strings, the StringBuilder class is for creating mutable strings, and the StringBuffer class is similar to StringBuilder except that StringBuffer contains synchronized methods for updating strings. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26
  • 27. Designing a Class, cont.  Classes are designed for reuse. Users can incorporate classes in many different combinations, orders, and environments. Therefore, you should design a class that imposes no restrictions on what or when the user can do with it, design the properties to ensure that the user can set properties in any order, with any combination of values, and design methods to function independently of their order of occurrence. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27
  • 28. Designing a Class, cont.  Providea public no-arg constructor and override the equals method and the toString method defined in the Object class whenever possible. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28
  • 29. Designing a Class, cont.  Follow standard Java programming style and naming conventions. Choose informative names for classes, data fields, and methods. Always place the data declaration before the constructor, and place constructors before methods. Always provide a constructor and initialize variables to avoid programming errors. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29
  • 30. Using Visibility Modifiers  Each class can present two contracts – one for the users of the class and one for the extenders of the class. Make the fields private and accessor methods public if they are intended for the users of the class. Make the fields or method protected if they are intended for extenders of the class. The contract for the extenders encompasses the contract for the users. The extended class may increase the visibility of an instance method from protected to public, or change its implementation, but you should never change the implementation in a way that violates that contract. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30
  • 31. Using Visibility Modifiers, cont. A class should use the private modifier to hide its data from direct access by clients. You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify. A class should also hide methods not intended for client use. The gcd method in the Rational class in Example 11.2, “The Rational Class,” is private, for example, because it is only for internal use within the class. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31
  • 32. Using the static Modifier A property that is shared by all the instances of the class should be declared as a static property. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32
  • 33. Wrapper Classes  Boolean  Integer NOTE: (1) The wrapper classes do not have no-arg constructors. (2)  Character  Long The instances of all wrapper classes are immutable, i.e., their  Short  Float internal values cannot be changed once the objects are created.  Byte  Double Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33
  • 34. The toString, equals, and hashCode Methods Each wrapper class overrides the toString, equals, and hashCode methods defined in the Object class. Since all the numeric wrapper classes and the Character class implement the Comparable interface, the compareTo method is implemented in these classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34
  • 35. The Integer and Double Classes java.lang.Integer java.lang.Double -value: int -value: double +MAX_VALUE: int +MAX_VALUE: double +MIN_VALUE: int +MIN_VALUE: double +Integer(value: int) +Double(value: double) +Integer(s: String) +Double(s: String) +byteValue(): byte +byteValue(): byte +shortValue(): short +shortValue(): short +intValue(): int +intValue(): int +longVlaue(): long +longVlaue(): long +floatValue(): float +floatValue(): float +doubleValue():double +doubleValue():double +compareTo(o: Integer): int +compareTo(o: Double): int +toString(): String +toString(): String +valueOf(s: String): Integer +valueOf(s: String): Double +valueOf(s: String, radix: int): Integer +valueOf(s: String, radix: int): Double +parseInt(s: String): int +parseDouble(s: String): double +parseInt(s: String, radix: int): int +parseDouble(s: String, radix: int): double Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35
  • 36. The Integer Class and the Double Class  Constructors  Class Constants MAX_VALUE, MIN_VALUE  Conversion Methods Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36
  • 37. Numeric Wrapper Class Constructors You can construct a wrapper object either from a primitive data type value or from a string representing the numeric value. The constructors for Integer and Double are: public Integer(int value) public Integer(String s) public Double(double value) public Double(String s) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37
  • 38. Numeric Wrapper Class Constants Each numerical wrapper class has the constants MAX_VALUE and MIN_VALUE. MAX_VALUE represents the maximum value of the corresponding primitive data type. For Byte, Short, Integer, and Long, MIN_VALUE represents the minimum byte, short, int, and long values. For Float and Double, MIN_VALUE represents the minimum positive float and double values. The following statements display the maximum integer (2,147,483,647), the minimum positive float (1.4E-45), and the maximum double floating-point number (1.79769313486231570e+308d). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38
  • 39. Conversion Methods Each numeric wrapper class implements the abstract methods doubleValue, floatValue, intValue, longValue, and shortValue, which are defined in the Number class. These methods “convert” objects into primitive type values. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39
  • 40. The Static valueOf Methods The numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example: Double doubleObject = Double.valueOf("12.4"); Integer integerObject = Integer.valueOf("12"); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40
  • 41. The Methods for Parsing Strings into Numbers You have used the parseInt method in the Integer class to parse a numeric string into an int value and the parseDouble method in the Double class to parse a numeric string into a double value. Each numeric wrapper class has two overloaded parsing methods to parse a numeric string into an appropriate numeric value. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41
  • 42. Automatic Conversion Between Primitive Types and Wrapper Class Types JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For example, the following statement in (a) can be simplified as in (b): Integer[] intArray = {new Integer(2), Equivalent Integer[] intArray = {2, 4, 3}; new Integer(4), new Integer(3)}; (a) New JDK 1.5 boxing (b) Integer[] intArray = {1, 2, 3}; System.out.println(intArray[0] + intArray[1] + intArray[2]); Unboxing Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42
  • 43. BigInteger and BigDecimal If you need to compute with very large integers or high precision floating-point values, you can use the BigInteger and BigDecimal classes in the java.math package. Both are immutable. Both extend the Number class and implement the Comparable interface. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 43
  • 44. BigInteger and BigDecimal BigInteger a = new BigInteger("9223372036854775807"); BigInteger b = new BigInteger("2"); BigInteger c = a.multiply(b); // 9223372036854775807 * 2 System.out.println(c); LargeFactorial Run BigDecimal a = new BigDecimal(1.0); BigDecimal b = new BigDecimal(3); BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP); System.out.println(c); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 44