0% found this document useful (0 votes)
33 views

Thinking in Objects

Uploaded by

jadjaffal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Thinking in Objects

Uploaded by

jadjaffal01
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter 10 - Thinking in Objects

Dr. ASEM KITANA


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

2
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
3
Class Relationships
 Association
 Aggregation
 Composition
 Inheritance (Later)
Association

Association is a general binary relationship that describes an activity between two classes

Examples:
 a student taking a course is an association between the Student class and the Course class
 faculty member teaching a course is an association between the Faculty class and the Course class
Association Labels

This UML diagram shows that


1. a student may take any number of courses a solid line
2. a faculty member may teach at most three courses between two
3. a course may have from five to sixty students classes
4. a course is taught by only one faculty member
Notes
 An association is illustrated by a solid line between two classes with an optional label
the labels are Take and Teach
Each relationship may have an optional small black triangle that indicates the direction of the
relationship
Each class involved in the relationship may have a role name that describes the role it plays in
the relationship. In previous Figure , teacher is the role name for Faculty.
 Each class involved in an association may specify a multiplicity, which is placed at the side of
the class to specify how many of the class’s objects are involved in the relationship in UML
A multiplicity could be a number or an interval that specifies how many of the class’s objects
are involved in the relationship
The character * means an unlimited number of objects, and the interval m..n indicates that
the number of objects is between m and n, inclusively.
Association in Javacode
Association in Javacode
In Java code, you can implement associations by using data fields and methods

The relation “a student takes a course” is implemented using:


the addCourse method in the Student class the
addStuent method in the Course class

The relation “a faculty teaches a course” is implemented using:


the addCourse method in the Faculty class the
setFaculty method in the Course class
Aggregation andComposition
Aggregation is a special form of association that represents an ownership relationship between two
objects.
Aggregation models has-a relationships
The owner object is called an aggregating object, and its class is called an aggregating class
The subject object is called an aggregated object, and its class is called an aggregated class.

An object can be owned by several other aggregating objects

 If an object is exclusively owned by an aggregating object, the relationship between the object
and its aggregating object is referred to as a composition
Examples(Aggregation andComposition)

• For example, “a student has a name” is a composition relationship


between the Student class and the Name class.

•Whereas “a student has an address” is an aggregation relationship


between the Student class and the Address class, since an address can
be shared by several students
Examples(Aggregation andComposition)

a filled diamond is attached to an aggregating class (in this case, Student) to denote the
composition relationship with an aggregated class (Name).

an empty diamond is attached to an aggregating class (Student) to denote the


aggregation relationship with an aggregated class (Address).
Aggregation and Composition inJava code
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.

14
Aggregation Between Same Class
Aggregation may exist between objects of the same class. For example, a
person may have a supervisor.

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
}

15
Aggregation Between Same Class
What happens if a person has several supervisors?

16
Examples (Car & Engine)

Composition ( engine just for one car)


Examples (Car & Driver)

Aggregation (shared between more than one


driver)
Example (Aggregation and Composition)

an account could belong to a transaction is part of an account,


more than one customer but it can not belong to more than
one account
Wrapper class in Java
A primitive data type value is not an object, but it can be wrapped in an object
using a wrapper class.
The wrapper class provides the mechanism to convert primitive into object and
object into primitive

autoboxing and unboxing feature converts primitive into object and object
into primitive automatically.

The automatic conversion of primitive into object is known as autoboxing


and vice-versa unboxing.
Wrapper class in Java
The eight classes of java.lang package are known as wrapper classes in java. The list of eight wrapper classes are given
below

These classes are called wrapper classes because each wraps or encapsulates a primitive type value in an object.
WrapperClasses
 Boolean NOTE:
 Character (1) The wrapper classes do not
 Short have no-arg constructors.
 Byte (2) The instances of all wrapper
 Integer classes are immutable, i.e.,
 Long their internal values cannot be
changed once the objects are
 Float created.
 Double

17
The Integer and Double Classes

18
TheInteger and Double Classes

 These methods convert objects into primitive values (unboxing):

doubleValue(), floatValue(), intValue(), longValue(), shortValue(), and


byteValue().

 You can construct a wrapper object either from a primitive data type value or
from a string representing the numeric value, by using the valueOf method
(autoboxing or boxing):

For example:
Double.valueOf(5.0), Double.valueOf("5.0"), Integer.valueOf(5), and
Integer.valueOf("5").
TheInteger and Double Classes

Creating Integer object:

Integer x1 = new Integer(32); new Integer(32);

Integer x2 = Integer.valueOf(32); Integer.valueOf(32);

Integer x3 = 32;

(It is preferred to use the valueOf method to create objects).

Double.valueOf(12.4).intValue( ) returns 12;

Integer.valueOf(12).doubleValue( ) returns 12.0;


TheInteger and Double Classes

Recall the String class contains the compareTo method for comparing two strings. The
numeric wrapper classes contain the compareTo method for comparing two numbers and
returns 1, 0, or –1, if this number is greater than, equal to, or less than the other number. For
example,

Double.valueOf(12.4).compareTo(Double.valueOf(12.3)) returns 1;

Double.valueOf(12.3).compareTo(Double.valueOf(12.3)) returns 0;

Double.valueOf(12.3).compareTo(Double.valueOf(12.51)) returns –1;


Examples
Integer a = new Integer("23"); //23

Integer b = new Integer(23); //23

Integer c = Integer.valueOf("23"); //23

Double d = new Double( ); // error (no no-arg constructor)

Double x = Double.valueOf("23.45"); //23.45

int y = (Integer.valueOf("23")).intValue( ); //23

double z = (Double.valueOf("23.4")).doubleValue( ); //23.4

int v = (Double.valueOf("23.4")).intValue( ); //23

String s = (Double.valueOf("23.4")).toString( ); //23.4


Examples

20
Examples

21
Numeric Wrapper ClassConstants
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.

22
ConversionMethods
Each numeric wrapper class implements the
abstract methods doubleValue, floatValue,
intValue, longValue, and shortValue, which are
defined in the Number class. (Number class is a
superclass for the wrapper classes).
These methods “convert” objects into
primitive type values.

23
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");

24
The Methods forParsing 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 based on 10 (decimal) or any specified
radix
(e.g., 2 for binary, 8 for octal, and 16 for hexadecimal).

25
Parsing Strings into Numbers
• Integer.parseInt("11", 2) returns 3;
• Integer.parseInt("12", 8) returns 10;
• Integer.parseInt("13", 10) returns 13;
• Integer.parseInt("1A", 16) returns 26;
• Integer.parseInt("12", 2) would raise a runtime exception
because 12 is not a binary number.
Automatic Conversion BetweenPrimitive
Typesand Wrapper ClassTypes
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[ ] arr = {1, 2, 3};

System.out.println(arr[0] + arr[1] + arr[2]);


Unboxing
(arithmetic operations such as addition are defined for primitive types, but not directly for
numeric wrapper objects)
BigInteger andBigDecimal

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.

27
BigIntegerandBigDecimal
The largest integer of the long type is Long.MAX_VALUE (i.e., 9223372036854775807).
An object of BigInteger can represent an integer of any size.

You can use new BigInteger(String) or BigInteger.valueOf(long) to create an instance of


BigInteger.

Also, you can use new BigDecimal(String), new BigDecimal(double) or


BigDecimal.valueOf(double) to create an instance of BigDecimal.

The methods add, subtract, multiply, divide, and remainder can be used to perform
arithmetic operations.
BigInteger andBigDecimal

BigInteger a = new BigInteger("9223372036854775807");


BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);

BigDecimal a = new BigDecimal(1.0);


BigDecimal b = new BigDecimal(3);
BigDecimal c = a.multiply(b);
System.out.println(c);
28
BigInteger
class

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
BigDecimal
class
BigInteger.ONE (line 9) is a constant defined in the BigInteger class. BigInteger.ONE is the
same as new BigInteger("1").

You might also like