SlideShare ist ein Scribd-Unternehmen logo
1 von 93
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
1
Chapter 3
Classes and Objects
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
2
3.1 Objects as Models
• A program can be thought of as a model of reality,
with objects in the program representing physical
objects.
• Properties of objects:
– State (information stored within the object)
– Behavior (operations that can be performed on the
object)
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
3
Example 1: Ball-point Pen
• The state of a ball-point pen with a retractable
point can be represented by two values:
– Is the point of the pen exposed?
– How much ink remains in the pen?
• Operations on a pen include:
– Press the button at the end of the pen.
– Move the pen with the point held against a sheet of
paper.
– Replace the pen’s cartridge.
– Determine how much ink remains in the pen.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
4
Example 2: Bank Account
• A state of a bank account includes the account
number, the balance, the transactions performed
on the account since it was opened, and so forth.
• For simplicity, let’s assume that the state of a bank
account consists of just the balance in the account.
• Operations on a bank account include:
– Deposit money into an account.
– Withdraw money from the account.
– Check the balance in the account.
– Close the account.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
5
Example 3: Car
• The state of a car includes the amount of fluids in
the car, the state of the tires, and even the
condition of each part in the car.
• For programming purposes, we can focus on just a
few elements of the state:
– Is the engine on?
– How much fuel remains in the car’s tank?
• Operations on a car include:
– Start the engine.
– Drive a specified distance.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
6
Artificial Objects
• Nearly every “real-world” object can be modeled
within a program.
• Programmers also work with artificial objects that
don’t correspond to objects in the physical world.
• Like all objects, these artificial objects have state
and behavior.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
7
3.2 Representing Objects Within a Program
• In Java, the state of an object is stored in instance
variables (or fields).
• The behavior of an object is represented by
instance methods.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
8
Instance Variables
• Some instance variables will store a single value.
Others may store entire objects.
• Instance variables needed for a ball-point pen:
– pointIsExposed (boolean)
– inkRemaining (double)
• Instance variables needed for a bank account:
– balance (double)
• Instance variables needed for a car:
– engineIsOn (boolean)
– fuelRemaining (double)
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
9
Instance Methods
• In Java, performing an operation on an object is
done by calling one of the instance methods
associated with the object.
• An instance method may require arguments when
it’s called, and it may return a value.
• When asked to perform an operation on an object,
an instance method can examine and/or change the
values stored in any of the object’s instance
variables.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
10
Examples of Instance Methods
• Instance methods for ball-point pens:
– pressButton:“Toggles” pointIsExposed.
– write: Reduces value of inkRemaining.
– replaceCartridge: Restores inkRemaining to
its maximum value.
– checkInkRemaining: Returns value of
inkRemaining.
• Instance methods for bank accounts:
– deposit: Adds an amount to balance.
– withdraw: Subtracts an amount from balance.
– getBalance: Returns value of balance.
– close: Stores zero into balance.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
11
Examples of Instance Methods
• Instance methods for cars:
– startEngine: Stores true into engineIsOn.
– stopEngine: Stores false into engineIsOn.
– drive: Reduces fuelRemaining by an amount
calculated by dividing the distance traveled by the
expected fuel consumption.
– addFuel: Increases fuelRemaining by a specified
amount.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
12
3.3 Classes
• The instance variables and instance methods that
belong to a particular kind of object are grouped
together into a class.
• Examples of classes:
– BallpointPen
– Account
– Car
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
13
Declaring a Class
• A class declaration contains declarations of
instance variables and instance methods.
• Most class declarations also contain declarations
of constructors, whose job is to initialize objects.
• Form of a class declaration:
public class class-name {
variable-declarations
constructor-declarations
method-declarations
}
• The order of declarations usually doesn’t matter.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
14
Access Modifiers
• The declaration of an instance variable, a
constructor, or an instance method usually begins
with an access modifier (public or private).
• An access modifier determines whether that entity
can be accessed by other classes (public) or
only within the class itself (private).
• The most common arrangement is for instance
variables to be private and constructors and
instance methods to be public.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
15
Declaring Instance Variables
• An instance variable declaration looks the same as
the declaration of a variable inside a method,
except that an access modifier is usually present:
private double balance;
• The only access to balance will be through the
instance methods in the Account class.
• The policy of making instance variables private is
known as information hiding.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
16
Declaring Instance Methods
• Parts of an instance method declaration:
– Access modifier
– Result type. If no value is returned, the result type is
void.
– Method name
– Parameters
– Body
• Outline of the deposit method:
public void deposit(double amount) {
…
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
17
Method Overloading
• Java allows methods to be overloaded.
Overloading occurs when a class contains more
than one method with the same name.
• The methods must have different numbers of
parameters or there must be some difference in the
types of the parameters.
• Overloading is best used for methods that perform
essentially the same operation.
• The advantage of overloading: Fewer method
names to remember.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
18
Declaring Constructors
• When an object is created, its instance variables
are initialized by a constructor.
• A constructor looks like an instance method,
except that it has no result type and its name is the
same as the name of the class itself.
• A constructor for the Account class:
public Account(double initialBalance) {
…
}
• A class may have more than one constructor.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
19
Example: An Account Class
Account.java
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account() {
balance = 0.0;
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
20
// Instance methods
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
public double getBalance() {
return balance;
}
public void close() {
balance = 0.0;
}
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
21
3.4 Creating Objects
• Once a class has been declared, it can be used to
create objects (instances of the class).
• Each instance will contain its own copy of the
instance variables declared in the class.
• A newly created object can be stored in a variable
whose type matches the object’s class:
Account acct;
Technically, acct will store a reference to an
Account object, not the object itself.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
22
The new Keyword
• The keyword new, when placed before a class
name, causes an instance of the class to be created.
• A newly created object can be stored in a variable:
acct = new Account(1000.00);
• The acct variable can be declared in the same
statement that creates the Account object:
Account acct = new Account(1000.00);
• An object can also be created using the second
constructor in the Account class:
acct = new Account();
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
23
3.5 Calling Instance Methods
• Once an object has been created, operations can be
performed on it by calling the instance methods in
the object’s class.
• Form of an instance method call:
object . method-name ( arguments )
The parentheses are mandatory, even if there are
no arguments.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
24
Calling Account Instance Methods
• Suppose that acct contains an instance of the
Account class.
• Example calls of Account instance methods:
acct.deposit(1000.00);
acct.withdraw(500.00);
acct.close();
• An object must be specified when an instance
method is called, because more than one instance
of the class could exist:
acct1.deposit(1000.00);
acct2.deposit(1000.00);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
25
Using the Value Returned
by an Instance Method
• When an instance method returns no result, a call
of the method is an entire statement:
acct.deposit(1000.00);
• When an instance method does return a result, that
result can be used in a variety of ways.
• One possibility is to store it in a variable:
double newBalance = acct.getBalance();
• Another possibility is to print it:
System.out.println(acct.getBalance());
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
26
How Instance Methods Work
• Sequence of events when an instance method is
called:
– The program “jumps” to that method.
– The arguments in the call are copied into the method’s
corresponding parameters.
– The method begins executing.
– When the method is finished, the program “returns” to
the point at which the method was called.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
27
3.6 Writing Programs with Multiple Classes
• A program that tests the Account class:
TestAccount.java
public class TestAccount {
public static void main(String[] args) {
Account acct1 = new Account(1000.00);
System.out.println("Balance in account 1: " +
acct1.getBalance());
acct1.deposit(100.00);
System.out.println("Balance in account 1: " +
acct1.getBalance());
acct1.withdraw(150.00);
System.out.println("Balance in account 1: " +
acct1.getBalance());
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
28
acct1.close();
System.out.println("Balance in account 1: " +
acct1.getBalance());
Account acct2 = new Account();
System.out.println("Balance in account 2: " +
acct2.getBalance());
acct2.deposit(500.00);
System.out.println("Balance in account 2: " +
acct2.getBalance());
acct2.withdraw(350.00);
System.out.println("Balance in account 2: " +
acct2.getBalance());
acct2.close();
System.out.println("Balance in account 2: " +
acct2.getBalance());
}
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
29
Output of the TestAccount program
Balance in account 1: 1000.0
Balance in account 1: 1100.0
Balance in account 1: 950.0
Balance in account 1: 0.0
Balance in account 2: 0.0
Balance in account 2: 500.0
Balance in account 2: 150.0
Balance in account 2: 0.0
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
30
Compiling a Program with Multiple Classes
• The TestAccount class, together with the
Account class, form a complete program.
• If the classes are stored in separate files, they
could be compiled using the following commands:
javac Account.java
javac TestAccount.java
• As an alternative, both files can be compiled with
a single command:
javac TestAccount.java
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
31
Compiling a Program with Multiple Classes
• When a file is compiled, the compiler checks
whether its dependent classes are up-to-date.
• If the .java file containing a dependent class has
been modified since the .class file was created,
javac will recompile the .java file
automatically.
• When TestAccount.java is compiled, the
javac compiler will look for Account.java
and compile it if necessary.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
32
Executing a Program with Multiple Classes
• Command to execute the TestAccount
program:
java TestAccount
The Account class is not mentioned.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
33
Using a Single File
• The Account and TestAccount classes can
be put in the same file.
– The file will need to be named TestAccount.java,
because TestAccount contains the main method.
– The public access modifier will have to be removed
from the beginning of the Account class declaration.
(Only one class in a file can be declared public.)
• Compiling TestAccount.java causes
TestAccount.class and Account.class
to be generated.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
34
Using a Single File
• It’s often better to put only one class in each file.
• Advantages:
– Classes are easier to locate.
– Files are smaller and easier to edit.
– If a class declaration is changed, only the class itself
will have to be recompiled.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
35
3.7 How Objects Are Stored
• A variable of an ordinary (non-object) type can be
visualized as a box:
int i;
• Assigning a value to the variable changes the
value stored in the box:
i = 0;
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
36
Object Variables
• An object variable, on the other hand, doesn’t
actually store an object. Instead, it will store a
reference to an object.
• An object variable can still be visualized as a box:
Account acct;
• Suppose that a new object is stored into acct:
acct = new Account(500.00);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
37
Object Variables
• The Account object isn’t stored in the acct
box. Instead, the box contains a reference that
“points to” the object:
• In many programming languages, including C++,
a variable such as acct would be called a pointer
variable.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
38
The null Keyword
• To indicate that an object variable doesn’t
currently point to an object, the variable can be
assigned the value null:
acct = null;
• When an object variable stores null, it’s illegal
to use the variable to call an instance method.
• If acct has the value null, executing the
following statement will cause a run-time error
(NullPointerException):
acct.deposit(500.00);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
39
Object Assignment
• If i has the value 10, assigning i to j gives j the
value 10 as well:
j = i;
• Changing the value of i has no effect on j:
i = 20;
• Assignment of objects doesn’t work the same way.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
40
Object Assignment
• Assume that acct1 contains a reference to an
Account object with a balance of $500.
• Assigning acct1 to acct2 causes acct2 to
refer to the same object as acct1:
acct2 = acct1;
• acct1 and acct2 are said to be aliases, because
both represent the same object.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
41
Object Assignment
• An operation that changes the acct1 object will
also change the acct2 object, and vice-versa.
• The statement
acct1.deposit(500.00);
will change the balance of acct2 to $1000.00:
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
42
Cloning
• Some classes allow the creation of a new object
that’s identical to an existing object.
• The new object is said to be a clone of the old one.
• Clones are created by calling the clone method.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
43
Garbage
• Objects can become “orphaned” during program
execution.
• Consider the following example:
acct1 = new Account(100.00);
acct2 = new Account(200.00);
acct1 = acct2;
• After these assignments, the object that acct1
previously referred to is lost. We say that it is
garbage.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
44
Garbage
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
45
Garbage Collection
• Java provides automatic garbage collection: as a
Java program runs, a software component known
as the garbage collector watches for garbage and
periodically “collects” it.
• The recycled memory can be used for the creation
of new objects.
• Garbage collection normally takes place when the
program isn’t doing any other useful activity.
• Java is the first widely used programming
language to incorporate garbage collection .
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
46
Memory Leaks
• Other popular languages rely on the program to
explicitly release memory that’s no longer needed.
• This practice is potentially more efficient, but it’s
also error-prone.
• Failing to recover garbage causes available
memory to decrease (a memory leak).
• After a period of time, a program with a memory
leak may run out of memory entirely.
• Releasing memory prematurely is even worse,
often causing programs to crash.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
47
3.8 Developing a Fraction Class
• Fractions can be thought of as objects, so it’s not
hard to develop a Fraction class.
• A Fraction object will need to store a
numerator and a denominator. Both are integers.
• There are many potential operations on fractions,
including adding, subtracting, multiplying, and
dividing.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
48
A First Attempt
• A first attempt at writing the Fraction class:
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int num, int denom) {
numerator = num;
denominator = denom;
}
// Methods will go here
}
• A Fraction object will be created as follows:
Fraction f = new Fraction(4, 8);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
49
Getters and Setters
• The Fraction class will need methods named
getNumerator and getDenominator:
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
• An instance method that does nothing but return
the value of an instance variable is said to be an
accessor (or a getter).
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
50
Getters and Setters
• By convention, names of getters start with the
word get.
• Sample calls of getNumerator and
getDenominator:
int num = f.getNumerator();
int denom = f.getDenominator();
• An instance method that stores its parameter into
an instance variable is said to be a mutator (or
setter).
• Names of setters begin with the word set.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
51
Getters and Setters
• Potential setters for the Fraction class:
public void setNumerator(int num) {
numerator = num;
}
public void setDenominator(int denom) {
denominator = denom;
}
• Sample calls of setNumerator and
setDenominator :
f.setNumerator(5);
f.setDenominator(6);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
52
Immutable Objects
• Setters can be useful, because they allow us to
change data stored in private variables.
• In some cases, however, we may not want to allow
changes to an object’s instance variables.
• Such an object is said to be immutable
(unchangeable).
• The advantage of making objects immutable is
that they can be shared without problems.
• Some of the classes in the Java API have this
property, including the String class.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
53
Writing the add Method
• A method that adds Fraction objects f1 and
f2 would need to be called in the following way:
Fraction f3 = f1.add(f2);
• add would have the following appearance:
public Fraction add(Fraction f) {
…
}
The parameter f represents the second of the two
fractions to be added.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
54
Writing the add Method
• A first attempt at writing the add method:
public Fraction add(Fraction f) {
int num = numerator * f.getDenominator() +
f.getNumerator() * denominator;
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
• numerator and denominator refer to the
numerator and denominator of the Fraction
object that’s calling add.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
55
Writing the add Method
• The add method can be shortened slightly by
combining the constructor call with the return
statement:
public Fraction add(Fraction f) {
int num = numerator * f.getDenominator() +
f.getNumerator() * denominator;
int denom = denominator * f.getDenominator();
return new Fraction(num, denom);
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
56
Writing the add Method
• The add method can be further simplified by
having it access f’s numerator and
denominator variables directly:
public Fraction add(Fraction f) {
int num = numerator * f.denominator +
f.numerator * denominator;
int denom = denominator * f.denominator;
return new Fraction(num, denom);
}
• Instance variables are accessed using a dot, just as
instance methods are called using a dot.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
57
Adding a toString Method
• The value stored in a Fraction object named f
could be printed in the following way:
System.out.println(f.getNumerator() + "/" +
f.getDenominator());
• The following method makes it easier to print
fractions:
public String toString() {
return numerator + "/" + denominator;
}
• In Java, the name toString is used for a
method that returns the contents of an object as a
string.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
58
Adding a toString Method
• The toString method makes it easier to display
the value stored in a Fraction object:
System.out.println(f.toString());
• The statement can be shortened even further:
System.out.println(f);
When given an object as its argument,
System.out.println will automatically call
the object’s toString method.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
59
3.9 Java’s String Class
• The Java API provides a huge number of
prewritten classes. Of these, the String class is
probably the most important.
• Instances of the String class represent strings of
characters.
• The String class belongs to a package named
java.lang.
• The java.lang package is automatically
imported into every program. (No other package
has this property.)
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
60
Creating Strings
• In Java, every string of characters, such as
"abc", is an instance of the String class.
• String variables can be assigned String
objects as their values:
String str1, str2;
• String is the only class whose instances can be
created without the word new:
str1 = "abc";
This is an example of magic.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
61
Visualizing a String
• A String object can be visualized as a series of
characters, with each character identified by its
position.
• The first character is located at position 0.
• A visual representation of the string "Java
rules!":
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
62
Common String Methods
• The String class has a large number of instance
methods.
• Assume that the following variable declarations
are in effect:
String str1 = "Fat cat", str2;
char ch;
int index;
• The charAt method returns the character stored
at a specific position in a string:
ch = str1.charAt(0); // Value of ch is now 'F'
ch = str1.charAt(6); // Value of ch is now 't'
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
63
Common String Methods
• One version of the indexOf method searches for
a string (the “search key”) within a larger string,
starting at the beginning of the larger string.
• Example: Locating the string "at" within str1:
index = str1.indexOf("at");
After this assignment, index will have the value 1.
• If "at" had not been found anywhere in str1,
indexOf would have returned –1.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
64
Common String Methods
• The other version of indexOf begins the search
at a specified position, rather than starting at
position 0.
• This version is particularly useful for repeating a
previous search to find another occurrence of the
search key.
• Example: Finding the second occurrence of "at"
in str1:
index = str1.indexOf("at", index + 1);
index will be assigned the value 5.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
65
Common String Methods
• lastIndexOf is similar to indexOf, except
that searches proceed backwards, starting from the
end of the string.
• Example: Finding the last occurrence of "at" in
str1:
index = str1.lastIndexOf("at");
The value of index after the assignment will be
5.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
66
Common String Methods
• The second version of lastIndexOf begins the
search at a specified position.
• Example: Finding the next-to-last occurrence of
"at":
index = str1.lastIndexOf("at", index - 1);
The value of index after the assignment will be
1.
• The String class has additional versions of
indexOf and lastIndexOf, whose first
argument is a single character rather than a string.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
67
Common String Methods
• The length method returns the number of
characters in a string.
• For example, str1.length() returns the
length of str1, which is 7.
• The substring method returns a substring: a
series of consecutive characters within a string.
• One version of substring selects a portion of a
string beginning at a specified position:
str2 = str1.substring(4);
After the assignment, str2 will have the value
"cat".
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
68
Common String Methods
• The other version of substring accepts two
arguments:
– The position of the first character to include in the
substring
– The position of the first character after the end of the
substring
• Example:
str2 = str1.substring(0, 3);
After the assignment, str2 will have the value
"Fat".
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
69
Common String Methods
• toLowerCase and toUpperCase will convert
the letters in a string to lowercase or uppercase.
• After the assignment
str2 = str1.toLowerCase();
the value of str2 is "fat cat".
• After the assignment
str2 = str1.toUpperCase();
the value of str2 is "FAT CAT".
• Characters other than letters aren’t changed by
toLowerCase and toUpperCase.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
70
Common String Methods
• The trim method removes spaces (and other
invisible characters) from both ends of a string.
• After the assignments
str1 = " How now, brown cow? ";
str2 = str1.trim();
the value of str2 will be
"How now, brown cow?"
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
71
Chaining Calls of Instance Methods
• When an instance method returns an object, that
object can be used to call another instance method.
• For example, the statements
str2 = str1.trim();
str2 = str2.toLowerCase();
can be combined into a single statement:
str2 = str1.trim().toLowerCase();
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
72
Using + to Concatenate Strings
• One of the most common string operations is
concatenation: joining two strings together to
form a single string.
• The String class provides a concat method
that performs concatenation, but it’s rarely used.
• Concatenation is so common that Java allows the
use of the plus sign (+) to concatenate strings:
str2 = str1 + "s";
str2 now contains the string "Fat cats".
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
73
Using + to Concatenate Strings
• The + operator works even if one of the operands
isn’t a String object. The non-String operand
is converted to string form automatically:
System.out.println("Celsius equivalent: " +
celsius);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
74
Using + to Concatenate Strings
• If the + operator is used to combine a string with
any other kind of object, the object’s toString
method is called.
• The statement
System.out.println("Value of fraction: " + f);
has the same effect as
System.out.println("Value of fraction: " +
f.toString());
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
75
Using + to Concatenate Strings
• In order for the + operator to mean string
concatenation, at least one of its two operands
must be a string:
System.out.println("Java" + 1 + 2);
// Prints "Java12"
System.out.println(1 + 2 + "Java");
// Prints "3Java"
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
76
Using + to Concatenate Strings
• The + operator is useful for breaking up long
strings into smaller chunks:
System.out.println(
"Bothered by unsightly white space? " +
"Remove it quickly andneasily with " +
"the new, improved trim method!");
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
77
Using + to Concatenate Strings
• The += operator can be used to add characters to
the end of a string:
String str = "The quick brown fox ";
str += "jumped over ";
str += "the lazy dog.";
The final value of str will be "The quick
brown fox jumped over the lazy dog."
• Concatenating a number with an empty string will
convert the number to string form. For example, if
i contains 37, then i + "" is the string "37".
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
78
Program: Decoding a Vehicle
Identification Number
• The manufacturer of a vehicle assigns it a unique
identifying number, called the Vehicle
Identification Number (VIN). A VIN packs a large
amount of information into a 17-character string:
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
79
The Check Digit in a VIN
• The check digit in a VIN is computed from the
other characters in the VIN; its purpose is to help
detect errors.
• The check digit algorithm used in vehicle
identification numbers will catch most common
errors, such as a single incorrect character or a
transposition of two characters.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
80
The VIN Program
• The VIN program will split a VIN into its
constituent pieces. The VIN is entered by the user
when prompted:
Enter VIN: JHMCB7658LC056658
World manufacturer identifier: JHM
Vehicle description section: CB765
Check digit: 8
Vehicle identification section: LC056658
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
81
VIN.java
// Displays information from a VIN entered by the user
import jpb.*;
public class VIN {
public static void main(String[] args) {
// Prompt the user to enter a VIN
SimpleIO.prompt("Enter VIN: ");
String vin = SimpleIO.readLine();
// Extract the parts of the VIN
String manufacturer = vin.substring(0, 3);
String description = vin.substring(3, 8);
String checkDigit = vin.substring(8, 9);
String identification = vin.substring(9);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
82
// Display the parts of the VIN
System.out.println("World manufacturer identifier: " +
manufacturer);
System.out.println("Vehicle description section: " +
description);
System.out.println("Check digit: " + checkDigit);
System.out.println("Vehicle identification section: " +
identification);
}
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
83
A Condensed Version of the VIN Program
VIN2.java
// Displays information from a VIN entered by the user
import jpb.*;
public class VIN2 {
public static void main(String[] args) {
// Prompt the user to enter a VIN
SimpleIO.prompt("Enter VIN: ");
String vin = SimpleIO.readLine();
// Display the parts of the VIN
System.out.println("World manufacturer identifier: " +
vin.substring(0, 3));
System.out.println("Vehicle description section: " +
vin.substring(3, 8));
System.out.println("Check digit: " + vin.substring(8, 9));
System.out.println("Vehicle identification section: " +
vin.substring(9));
}
}
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
84
3.10 Case Study: Checking
an ISBN Number
• An ISBN (International Standard Book Number)
is a unique number assigned to a book when it’s
published, such as 0–393–96945–2.
• The number at the end is a check digit that’s
calculated from the other digits in the ISBN.
• Our goal is to write a program named
CheckISBN that calculates the check digit for an
ISBN entered by the user:
Enter ISBN: 0-393-96945-2
Check digit entered: 2
Check digit computed: 2
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
85
Design of the CheckISBN Program
• The CheckISBN program will have four steps:
1. Prompt the user to enter an ISBN.
2. Compute the check digit for the ISBN.
3. Display the check digit entered by the user.
4. Display the computed check digit.
• The ISBN will be stored as a string, and the other
variables will be integers.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
86
Computing the Check Digit
• The check digit is calculated by multiplying the
first nine digits in the number by 10, 9, 8, …, 2,
respectively, and summing these products to get a
value we’ll call total.
• The check digit is now determined by the
expression
10 – ((total – 1) mod 11)
• The value of this expression is a number between
0 and 10. If the value is 10, the check digit is X.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
87
Computing the Check Digit
• Computation of the check digit for the ISBN 0–
393–96945–2:
total = 0 × 10 + 3 × 9 + 9 × 8 + 3 × 7 + 9 × 6 + 6 × 5 + 9 × 4 + 4 × 3 + 5 × 2
= 0 + 27 + 72 + 21 + 54 + 30 + 36 + 12 + 10
= 262
Check digit: 10 – ((262 – 1) mod 11) = 10 – (261 mod 11) = 10 – 8 = 2
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
88
Extracting Digits from the ISBN
• In order to compute the check digit, the first nine
digits in the ISBN must be extracted and
converted to numeric form.
• Since the position of the first two dashes may
vary, the program will need to search for them.
• Once the dashes have been found, the program can
extract the language code, publisher, and book
number and join these into a single string, the
“reduced ISBN.”
• If the original ISBN is "0-393-96945-2", the
reduced ISBN will be "039396945".
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
89
Extracting Digits from the ISBN
• Searching for the dashes can be done by calling
the indexOf method.
• The substring method can extract a portion of
the original ISBN.
• The + operator can put the pieces together to form
the reduced ISBN.
• The following expression extracts a digit and
converts it to a number:
Integer.parseInt(reducedISBN.substring(i, i + 1))
i is the position of the digit in the reduced ISBN.
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
90
Displaying the Check Digit
• If the check digit is 10, the program will need to
display the letter X instead of a normal digit.
• This problem can be solved by creating a string
containing the digits from 0 to 9, plus the letter X:
final String DIGITS = "0123456789X";
• The value of the check digit can be used to select
one of the characters in DIGITS. If the check
digit is stored in the variable checkDigit, the
expression will be
DIGITS.charAt(checkDigit)
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
91
CheckISBN.java
// Program name: CheckISBN
// Author: K. N. King
// Written: 1998-04-17
// Modified: 1999-02-11
//
// Prompts the user to enter an ISBN number. Computes the
// check digit for the ISBN. Displays both the check digit
// entered by the user and the check digit computed by the
// program.
import jpb.*;
public class CheckISBN {
public static void main(String[] args) {
// Prompt the user to enter an ISBN
SimpleIO.prompt("Enter ISBN: ");
String originalISBN = SimpleIO.readLine();
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
92
// Determine location of dashes
int dashPos1 = originalISBN.indexOf("-");
int dashPos2 = originalISBN.indexOf("-", dashPos1 + 1);
// Remove dashes from ISBN
String reducedISBN =
originalISBN.substring(0, dashPos1) +
originalISBN.substring(dashPos1 + 1, dashPos2) +
originalISBN.substring(dashPos2 + 1, 11);
// Compute the check digit for the ISBN
int total =
10 * Integer.parseInt(reducedISBN.substring(0, 1)) +
9 * Integer.parseInt(reducedISBN.substring(1, 2)) +
8 * Integer.parseInt(reducedISBN.substring(2, 3)) +
7 * Integer.parseInt(reducedISBN.substring(3, 4)) +
6 * Integer.parseInt(reducedISBN.substring(4, 5)) +
5 * Integer.parseInt(reducedISBN.substring(5, 6)) +
4 * Integer.parseInt(reducedISBN.substring(6, 7)) +
3 * Integer.parseInt(reducedISBN.substring(7, 8)) +
2 * Integer.parseInt(reducedISBN.substring(8, 9));
int checkDigit = 10 - ((total - 1) % 11);
Chapter 3: Classes and Objects
JavaJava ProgrammingProgramming
FROMTHEBEGINNINGFROMTHEBEGINNING
Copyright © 2000 W. W. Norton & Company.
All rights reserved.
93
// Display the check digit entered by the user
System.out.println("Check digit entered: " +
originalISBN.charAt(12));
// Display the computed check digit
final String DIGITS = "0123456789X";
System.out.println("Check digit computed: " +
DIGITS.charAt(checkDigit));
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
 
Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5prakash185645
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Sakthi Durai
 
Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)SURBHI SAROHA
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptUsman Mehmood
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Uzair Salman
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netbantamlak dejene
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basicsvamshimahi
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPRick Ogden
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Oops abap fundamental
Oops abap fundamentalOops abap fundamental
Oops abap fundamentalbiswajit2015
 
Unit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfUnit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfArpana Awasthi
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1bharath yelugula
 
Week08
Week08Week08
Week08hccit
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 

Was ist angesagt? (19)

Abap Objects for BW
Abap Objects for BWAbap Objects for BW
Abap Objects for BW
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5Oo abap-sap-1206973306636228-5
Oo abap-sap-1206973306636228-5
 
Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1 Java Programming Paradigms Chapter 1
Java Programming Paradigms Chapter 1
 
Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Java Variable Types
Java Variable TypesJava Variable Types
Java Variable Types
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.net
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Beginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHPBeginners Guide to Object Orientation in PHP
Beginners Guide to Object Orientation in PHP
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Oops abap fundamental
Oops abap fundamentalOops abap fundamental
Oops abap fundamental
 
Unit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdfUnit 2 Part 1 POLYMORPHISM.pdf
Unit 2 Part 1 POLYMORPHISM.pdf
 
Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1Objectorientedprogrammingmodel1
Objectorientedprogrammingmodel1
 
Week08
Week08Week08
Week08
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 

Andere mochten auch

Community workers game 2nd
Community workers game 2ndCommunity workers game 2nd
Community workers game 2ndNora Gonzalez
 
Stan's SSOT Forecast Model - Accruals Focus
Stan's SSOT Forecast Model - Accruals FocusStan's SSOT Forecast Model - Accruals Focus
Stan's SSOT Forecast Model - Accruals FocusStanley Chan
 
K seebeck weekend1
K seebeck weekend1K seebeck weekend1
K seebeck weekend1KellySeebeck
 
Mali 2010215039
Mali 2010215039Mali 2010215039
Mali 2010215039Kaan Cingi
 
Steel flanges stainless,Forged flanges
Steel flanges stainless,Forged flangesSteel flanges stainless,Forged flanges
Steel flanges stainless,Forged flangesMechwell Fittings
 
Bilişim etiği ve öğretimi
Bilişim etiği ve öğretimiBilişim etiği ve öğretimi
Bilişim etiği ve öğretimiKaan Cingi
 
20130607 arecs web_forecast_video_autumn_sun
20130607 arecs web_forecast_video_autumn_sun20130607 arecs web_forecast_video_autumn_sun
20130607 arecs web_forecast_video_autumn_sungtarabanoff
 
Căn hộ Vista Verde - LH: 0918.77.83.85
Căn hộ Vista Verde - LH: 0918.77.83.85Căn hộ Vista Verde - LH: 0918.77.83.85
Căn hộ Vista Verde - LH: 0918.77.83.85Fong Le
 
Affiliate Marketers on September 11, 2001
Affiliate Marketers on September 11, 2001Affiliate Marketers on September 11, 2001
Affiliate Marketers on September 11, 2001Shawn Collins
 

Andere mochten auch (12)

Community workers game 2nd
Community workers game 2ndCommunity workers game 2nd
Community workers game 2nd
 
Stan's SSOT Forecast Model - Accruals Focus
Stan's SSOT Forecast Model - Accruals FocusStan's SSOT Forecast Model - Accruals Focus
Stan's SSOT Forecast Model - Accruals Focus
 
K seebeck weekend1
K seebeck weekend1K seebeck weekend1
K seebeck weekend1
 
Literator April 2008
Literator April 2008Literator April 2008
Literator April 2008
 
Mali 2010215039
Mali 2010215039Mali 2010215039
Mali 2010215039
 
Steel flanges stainless,Forged flanges
Steel flanges stainless,Forged flangesSteel flanges stainless,Forged flanges
Steel flanges stainless,Forged flanges
 
Bilişim etiği ve öğretimi
Bilişim etiği ve öğretimiBilişim etiği ve öğretimi
Bilişim etiği ve öğretimi
 
20130607 arecs web_forecast_video_autumn_sun
20130607 arecs web_forecast_video_autumn_sun20130607 arecs web_forecast_video_autumn_sun
20130607 arecs web_forecast_video_autumn_sun
 
My community 2nd
My community  2ndMy community  2nd
My community 2nd
 
Căn hộ Vista Verde - LH: 0918.77.83.85
Căn hộ Vista Verde - LH: 0918.77.83.85Căn hộ Vista Verde - LH: 0918.77.83.85
Căn hộ Vista Verde - LH: 0918.77.83.85
 
Affiliate Marketers on September 11, 2001
Affiliate Marketers on September 11, 2001Affiliate Marketers on September 11, 2001
Affiliate Marketers on September 11, 2001
 
How to clean your baseball uniform
How to clean your baseball uniformHow to clean your baseball uniform
How to clean your baseball uniform
 

Ähnlich wie Ch. 3 classes and objects

Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Core java-course-content
Core java-course-contentCore java-course-content
Core java-course-contentAmanCSE1
 
Core java-training-course-content
Core java-training-course-contentCore java-training-course-content
Core java-training-course-contentvenkateshcs6
 
Core java-course-content
Core java-course-contentCore java-course-content
Core java-course-contentAmanCSE1
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRatnaJava
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1Geophery sanga
 
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
 
1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptxumarAnjum6
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxOOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxuzairrrfr
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#Muhammad Younis
 
Effective java
Effective javaEffective java
Effective javaEmprovise
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptxJUNSHIN8
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfArpana Awasthi
 

Ähnlich wie Ch. 3 classes and objects (20)

Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Core java-course-content
Core java-course-contentCore java-course-content
Core java-course-content
 
Core java-training-course-content
Core java-training-course-contentCore java-training-course-content
Core java-training-course-content
 
Core java-course-content
Core java-course-contentCore java-course-content
Core java-course-content
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
 
Java script
Java scriptJava script
Java script
 
java.pptx
java.pptxjava.pptx
java.pptx
 
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
 
1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx1_Object Oriented Programming.pptx
1_Object Oriented Programming.pptx
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptxOOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Object Oriented Programming C#
Object Oriented Programming C#Object Oriented Programming C#
Object Oriented Programming C#
 
Effective java
Effective javaEffective java
Effective java
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
IP Unit 2.pptx
IP Unit 2.pptxIP Unit 2.pptx
IP Unit 2.pptx
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptx
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
 

Kürzlich hochgeladen

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
"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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Kürzlich hochgeladen (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Ch. 3 classes and objects

  • 1. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Classes and Objects
  • 2. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 2 3.1 Objects as Models • A program can be thought of as a model of reality, with objects in the program representing physical objects. • Properties of objects: – State (information stored within the object) – Behavior (operations that can be performed on the object)
  • 3. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 3 Example 1: Ball-point Pen • The state of a ball-point pen with a retractable point can be represented by two values: – Is the point of the pen exposed? – How much ink remains in the pen? • Operations on a pen include: – Press the button at the end of the pen. – Move the pen with the point held against a sheet of paper. – Replace the pen’s cartridge. – Determine how much ink remains in the pen.
  • 4. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 4 Example 2: Bank Account • A state of a bank account includes the account number, the balance, the transactions performed on the account since it was opened, and so forth. • For simplicity, let’s assume that the state of a bank account consists of just the balance in the account. • Operations on a bank account include: – Deposit money into an account. – Withdraw money from the account. – Check the balance in the account. – Close the account.
  • 5. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 5 Example 3: Car • The state of a car includes the amount of fluids in the car, the state of the tires, and even the condition of each part in the car. • For programming purposes, we can focus on just a few elements of the state: – Is the engine on? – How much fuel remains in the car’s tank? • Operations on a car include: – Start the engine. – Drive a specified distance.
  • 6. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 6 Artificial Objects • Nearly every “real-world” object can be modeled within a program. • Programmers also work with artificial objects that don’t correspond to objects in the physical world. • Like all objects, these artificial objects have state and behavior.
  • 7. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 7 3.2 Representing Objects Within a Program • In Java, the state of an object is stored in instance variables (or fields). • The behavior of an object is represented by instance methods.
  • 8. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 8 Instance Variables • Some instance variables will store a single value. Others may store entire objects. • Instance variables needed for a ball-point pen: – pointIsExposed (boolean) – inkRemaining (double) • Instance variables needed for a bank account: – balance (double) • Instance variables needed for a car: – engineIsOn (boolean) – fuelRemaining (double)
  • 9. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 9 Instance Methods • In Java, performing an operation on an object is done by calling one of the instance methods associated with the object. • An instance method may require arguments when it’s called, and it may return a value. • When asked to perform an operation on an object, an instance method can examine and/or change the values stored in any of the object’s instance variables.
  • 10. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 10 Examples of Instance Methods • Instance methods for ball-point pens: – pressButton:“Toggles” pointIsExposed. – write: Reduces value of inkRemaining. – replaceCartridge: Restores inkRemaining to its maximum value. – checkInkRemaining: Returns value of inkRemaining. • Instance methods for bank accounts: – deposit: Adds an amount to balance. – withdraw: Subtracts an amount from balance. – getBalance: Returns value of balance. – close: Stores zero into balance.
  • 11. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 11 Examples of Instance Methods • Instance methods for cars: – startEngine: Stores true into engineIsOn. – stopEngine: Stores false into engineIsOn. – drive: Reduces fuelRemaining by an amount calculated by dividing the distance traveled by the expected fuel consumption. – addFuel: Increases fuelRemaining by a specified amount.
  • 12. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 12 3.3 Classes • The instance variables and instance methods that belong to a particular kind of object are grouped together into a class. • Examples of classes: – BallpointPen – Account – Car
  • 13. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 13 Declaring a Class • A class declaration contains declarations of instance variables and instance methods. • Most class declarations also contain declarations of constructors, whose job is to initialize objects. • Form of a class declaration: public class class-name { variable-declarations constructor-declarations method-declarations } • The order of declarations usually doesn’t matter.
  • 14. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 14 Access Modifiers • The declaration of an instance variable, a constructor, or an instance method usually begins with an access modifier (public or private). • An access modifier determines whether that entity can be accessed by other classes (public) or only within the class itself (private). • The most common arrangement is for instance variables to be private and constructors and instance methods to be public.
  • 15. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 15 Declaring Instance Variables • An instance variable declaration looks the same as the declaration of a variable inside a method, except that an access modifier is usually present: private double balance; • The only access to balance will be through the instance methods in the Account class. • The policy of making instance variables private is known as information hiding.
  • 16. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 16 Declaring Instance Methods • Parts of an instance method declaration: – Access modifier – Result type. If no value is returned, the result type is void. – Method name – Parameters – Body • Outline of the deposit method: public void deposit(double amount) { … }
  • 17. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 17 Method Overloading • Java allows methods to be overloaded. Overloading occurs when a class contains more than one method with the same name. • The methods must have different numbers of parameters or there must be some difference in the types of the parameters. • Overloading is best used for methods that perform essentially the same operation. • The advantage of overloading: Fewer method names to remember.
  • 18. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 18 Declaring Constructors • When an object is created, its instance variables are initialized by a constructor. • A constructor looks like an instance method, except that it has no result type and its name is the same as the name of the class itself. • A constructor for the Account class: public Account(double initialBalance) { … } • A class may have more than one constructor.
  • 19. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 19 Example: An Account Class Account.java public class Account { // Instance variables private double balance; // Constructors public Account(double initialBalance) { balance = initialBalance; } public Account() { balance = 0.0; }
  • 20. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 20 // Instance methods public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } public void close() { balance = 0.0; } }
  • 21. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 21 3.4 Creating Objects • Once a class has been declared, it can be used to create objects (instances of the class). • Each instance will contain its own copy of the instance variables declared in the class. • A newly created object can be stored in a variable whose type matches the object’s class: Account acct; Technically, acct will store a reference to an Account object, not the object itself.
  • 22. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 22 The new Keyword • The keyword new, when placed before a class name, causes an instance of the class to be created. • A newly created object can be stored in a variable: acct = new Account(1000.00); • The acct variable can be declared in the same statement that creates the Account object: Account acct = new Account(1000.00); • An object can also be created using the second constructor in the Account class: acct = new Account();
  • 23. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 23 3.5 Calling Instance Methods • Once an object has been created, operations can be performed on it by calling the instance methods in the object’s class. • Form of an instance method call: object . method-name ( arguments ) The parentheses are mandatory, even if there are no arguments.
  • 24. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 24 Calling Account Instance Methods • Suppose that acct contains an instance of the Account class. • Example calls of Account instance methods: acct.deposit(1000.00); acct.withdraw(500.00); acct.close(); • An object must be specified when an instance method is called, because more than one instance of the class could exist: acct1.deposit(1000.00); acct2.deposit(1000.00);
  • 25. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 25 Using the Value Returned by an Instance Method • When an instance method returns no result, a call of the method is an entire statement: acct.deposit(1000.00); • When an instance method does return a result, that result can be used in a variety of ways. • One possibility is to store it in a variable: double newBalance = acct.getBalance(); • Another possibility is to print it: System.out.println(acct.getBalance());
  • 26. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 26 How Instance Methods Work • Sequence of events when an instance method is called: – The program “jumps” to that method. – The arguments in the call are copied into the method’s corresponding parameters. – The method begins executing. – When the method is finished, the program “returns” to the point at which the method was called.
  • 27. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 27 3.6 Writing Programs with Multiple Classes • A program that tests the Account class: TestAccount.java public class TestAccount { public static void main(String[] args) { Account acct1 = new Account(1000.00); System.out.println("Balance in account 1: " + acct1.getBalance()); acct1.deposit(100.00); System.out.println("Balance in account 1: " + acct1.getBalance()); acct1.withdraw(150.00); System.out.println("Balance in account 1: " + acct1.getBalance());
  • 28. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 28 acct1.close(); System.out.println("Balance in account 1: " + acct1.getBalance()); Account acct2 = new Account(); System.out.println("Balance in account 2: " + acct2.getBalance()); acct2.deposit(500.00); System.out.println("Balance in account 2: " + acct2.getBalance()); acct2.withdraw(350.00); System.out.println("Balance in account 2: " + acct2.getBalance()); acct2.close(); System.out.println("Balance in account 2: " + acct2.getBalance()); } }
  • 29. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 29 Output of the TestAccount program Balance in account 1: 1000.0 Balance in account 1: 1100.0 Balance in account 1: 950.0 Balance in account 1: 0.0 Balance in account 2: 0.0 Balance in account 2: 500.0 Balance in account 2: 150.0 Balance in account 2: 0.0
  • 30. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 30 Compiling a Program with Multiple Classes • The TestAccount class, together with the Account class, form a complete program. • If the classes are stored in separate files, they could be compiled using the following commands: javac Account.java javac TestAccount.java • As an alternative, both files can be compiled with a single command: javac TestAccount.java
  • 31. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 31 Compiling a Program with Multiple Classes • When a file is compiled, the compiler checks whether its dependent classes are up-to-date. • If the .java file containing a dependent class has been modified since the .class file was created, javac will recompile the .java file automatically. • When TestAccount.java is compiled, the javac compiler will look for Account.java and compile it if necessary.
  • 32. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 32 Executing a Program with Multiple Classes • Command to execute the TestAccount program: java TestAccount The Account class is not mentioned.
  • 33. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 33 Using a Single File • The Account and TestAccount classes can be put in the same file. – The file will need to be named TestAccount.java, because TestAccount contains the main method. – The public access modifier will have to be removed from the beginning of the Account class declaration. (Only one class in a file can be declared public.) • Compiling TestAccount.java causes TestAccount.class and Account.class to be generated.
  • 34. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 34 Using a Single File • It’s often better to put only one class in each file. • Advantages: – Classes are easier to locate. – Files are smaller and easier to edit. – If a class declaration is changed, only the class itself will have to be recompiled.
  • 35. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 35 3.7 How Objects Are Stored • A variable of an ordinary (non-object) type can be visualized as a box: int i; • Assigning a value to the variable changes the value stored in the box: i = 0;
  • 36. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 36 Object Variables • An object variable, on the other hand, doesn’t actually store an object. Instead, it will store a reference to an object. • An object variable can still be visualized as a box: Account acct; • Suppose that a new object is stored into acct: acct = new Account(500.00);
  • 37. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 37 Object Variables • The Account object isn’t stored in the acct box. Instead, the box contains a reference that “points to” the object: • In many programming languages, including C++, a variable such as acct would be called a pointer variable.
  • 38. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 38 The null Keyword • To indicate that an object variable doesn’t currently point to an object, the variable can be assigned the value null: acct = null; • When an object variable stores null, it’s illegal to use the variable to call an instance method. • If acct has the value null, executing the following statement will cause a run-time error (NullPointerException): acct.deposit(500.00);
  • 39. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 39 Object Assignment • If i has the value 10, assigning i to j gives j the value 10 as well: j = i; • Changing the value of i has no effect on j: i = 20; • Assignment of objects doesn’t work the same way.
  • 40. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 40 Object Assignment • Assume that acct1 contains a reference to an Account object with a balance of $500. • Assigning acct1 to acct2 causes acct2 to refer to the same object as acct1: acct2 = acct1; • acct1 and acct2 are said to be aliases, because both represent the same object.
  • 41. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 41 Object Assignment • An operation that changes the acct1 object will also change the acct2 object, and vice-versa. • The statement acct1.deposit(500.00); will change the balance of acct2 to $1000.00:
  • 42. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 42 Cloning • Some classes allow the creation of a new object that’s identical to an existing object. • The new object is said to be a clone of the old one. • Clones are created by calling the clone method.
  • 43. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 43 Garbage • Objects can become “orphaned” during program execution. • Consider the following example: acct1 = new Account(100.00); acct2 = new Account(200.00); acct1 = acct2; • After these assignments, the object that acct1 previously referred to is lost. We say that it is garbage.
  • 44. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 44 Garbage
  • 45. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 45 Garbage Collection • Java provides automatic garbage collection: as a Java program runs, a software component known as the garbage collector watches for garbage and periodically “collects” it. • The recycled memory can be used for the creation of new objects. • Garbage collection normally takes place when the program isn’t doing any other useful activity. • Java is the first widely used programming language to incorporate garbage collection .
  • 46. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 46 Memory Leaks • Other popular languages rely on the program to explicitly release memory that’s no longer needed. • This practice is potentially more efficient, but it’s also error-prone. • Failing to recover garbage causes available memory to decrease (a memory leak). • After a period of time, a program with a memory leak may run out of memory entirely. • Releasing memory prematurely is even worse, often causing programs to crash.
  • 47. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 47 3.8 Developing a Fraction Class • Fractions can be thought of as objects, so it’s not hard to develop a Fraction class. • A Fraction object will need to store a numerator and a denominator. Both are integers. • There are many potential operations on fractions, including adding, subtracting, multiplying, and dividing.
  • 48. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 48 A First Attempt • A first attempt at writing the Fraction class: public class Fraction { private int numerator; private int denominator; public Fraction(int num, int denom) { numerator = num; denominator = denom; } // Methods will go here } • A Fraction object will be created as follows: Fraction f = new Fraction(4, 8);
  • 49. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 49 Getters and Setters • The Fraction class will need methods named getNumerator and getDenominator: public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } • An instance method that does nothing but return the value of an instance variable is said to be an accessor (or a getter).
  • 50. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 50 Getters and Setters • By convention, names of getters start with the word get. • Sample calls of getNumerator and getDenominator: int num = f.getNumerator(); int denom = f.getDenominator(); • An instance method that stores its parameter into an instance variable is said to be a mutator (or setter). • Names of setters begin with the word set.
  • 51. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 51 Getters and Setters • Potential setters for the Fraction class: public void setNumerator(int num) { numerator = num; } public void setDenominator(int denom) { denominator = denom; } • Sample calls of setNumerator and setDenominator : f.setNumerator(5); f.setDenominator(6);
  • 52. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 52 Immutable Objects • Setters can be useful, because they allow us to change data stored in private variables. • In some cases, however, we may not want to allow changes to an object’s instance variables. • Such an object is said to be immutable (unchangeable). • The advantage of making objects immutable is that they can be shared without problems. • Some of the classes in the Java API have this property, including the String class.
  • 53. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 53 Writing the add Method • A method that adds Fraction objects f1 and f2 would need to be called in the following way: Fraction f3 = f1.add(f2); • add would have the following appearance: public Fraction add(Fraction f) { … } The parameter f represents the second of the two fractions to be added.
  • 54. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 54 Writing the add Method • A first attempt at writing the add method: public Fraction add(Fraction f) { int num = numerator * f.getDenominator() + f.getNumerator() * denominator; int denom = denominator * f.getDenominator(); Fraction result = new Fraction(num, denom); return result; } • numerator and denominator refer to the numerator and denominator of the Fraction object that’s calling add.
  • 55. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 55 Writing the add Method • The add method can be shortened slightly by combining the constructor call with the return statement: public Fraction add(Fraction f) { int num = numerator * f.getDenominator() + f.getNumerator() * denominator; int denom = denominator * f.getDenominator(); return new Fraction(num, denom); }
  • 56. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 56 Writing the add Method • The add method can be further simplified by having it access f’s numerator and denominator variables directly: public Fraction add(Fraction f) { int num = numerator * f.denominator + f.numerator * denominator; int denom = denominator * f.denominator; return new Fraction(num, denom); } • Instance variables are accessed using a dot, just as instance methods are called using a dot.
  • 57. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 57 Adding a toString Method • The value stored in a Fraction object named f could be printed in the following way: System.out.println(f.getNumerator() + "/" + f.getDenominator()); • The following method makes it easier to print fractions: public String toString() { return numerator + "/" + denominator; } • In Java, the name toString is used for a method that returns the contents of an object as a string.
  • 58. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 58 Adding a toString Method • The toString method makes it easier to display the value stored in a Fraction object: System.out.println(f.toString()); • The statement can be shortened even further: System.out.println(f); When given an object as its argument, System.out.println will automatically call the object’s toString method.
  • 59. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 59 3.9 Java’s String Class • The Java API provides a huge number of prewritten classes. Of these, the String class is probably the most important. • Instances of the String class represent strings of characters. • The String class belongs to a package named java.lang. • The java.lang package is automatically imported into every program. (No other package has this property.)
  • 60. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 60 Creating Strings • In Java, every string of characters, such as "abc", is an instance of the String class. • String variables can be assigned String objects as their values: String str1, str2; • String is the only class whose instances can be created without the word new: str1 = "abc"; This is an example of magic.
  • 61. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 61 Visualizing a String • A String object can be visualized as a series of characters, with each character identified by its position. • The first character is located at position 0. • A visual representation of the string "Java rules!":
  • 62. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 62 Common String Methods • The String class has a large number of instance methods. • Assume that the following variable declarations are in effect: String str1 = "Fat cat", str2; char ch; int index; • The charAt method returns the character stored at a specific position in a string: ch = str1.charAt(0); // Value of ch is now 'F' ch = str1.charAt(6); // Value of ch is now 't'
  • 63. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 63 Common String Methods • One version of the indexOf method searches for a string (the “search key”) within a larger string, starting at the beginning of the larger string. • Example: Locating the string "at" within str1: index = str1.indexOf("at"); After this assignment, index will have the value 1. • If "at" had not been found anywhere in str1, indexOf would have returned –1.
  • 64. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 64 Common String Methods • The other version of indexOf begins the search at a specified position, rather than starting at position 0. • This version is particularly useful for repeating a previous search to find another occurrence of the search key. • Example: Finding the second occurrence of "at" in str1: index = str1.indexOf("at", index + 1); index will be assigned the value 5.
  • 65. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 65 Common String Methods • lastIndexOf is similar to indexOf, except that searches proceed backwards, starting from the end of the string. • Example: Finding the last occurrence of "at" in str1: index = str1.lastIndexOf("at"); The value of index after the assignment will be 5.
  • 66. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 66 Common String Methods • The second version of lastIndexOf begins the search at a specified position. • Example: Finding the next-to-last occurrence of "at": index = str1.lastIndexOf("at", index - 1); The value of index after the assignment will be 1. • The String class has additional versions of indexOf and lastIndexOf, whose first argument is a single character rather than a string.
  • 67. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 67 Common String Methods • The length method returns the number of characters in a string. • For example, str1.length() returns the length of str1, which is 7. • The substring method returns a substring: a series of consecutive characters within a string. • One version of substring selects a portion of a string beginning at a specified position: str2 = str1.substring(4); After the assignment, str2 will have the value "cat".
  • 68. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 68 Common String Methods • The other version of substring accepts two arguments: – The position of the first character to include in the substring – The position of the first character after the end of the substring • Example: str2 = str1.substring(0, 3); After the assignment, str2 will have the value "Fat".
  • 69. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 69 Common String Methods • toLowerCase and toUpperCase will convert the letters in a string to lowercase or uppercase. • After the assignment str2 = str1.toLowerCase(); the value of str2 is "fat cat". • After the assignment str2 = str1.toUpperCase(); the value of str2 is "FAT CAT". • Characters other than letters aren’t changed by toLowerCase and toUpperCase.
  • 70. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 70 Common String Methods • The trim method removes spaces (and other invisible characters) from both ends of a string. • After the assignments str1 = " How now, brown cow? "; str2 = str1.trim(); the value of str2 will be "How now, brown cow?"
  • 71. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 71 Chaining Calls of Instance Methods • When an instance method returns an object, that object can be used to call another instance method. • For example, the statements str2 = str1.trim(); str2 = str2.toLowerCase(); can be combined into a single statement: str2 = str1.trim().toLowerCase();
  • 72. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 72 Using + to Concatenate Strings • One of the most common string operations is concatenation: joining two strings together to form a single string. • The String class provides a concat method that performs concatenation, but it’s rarely used. • Concatenation is so common that Java allows the use of the plus sign (+) to concatenate strings: str2 = str1 + "s"; str2 now contains the string "Fat cats".
  • 73. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 73 Using + to Concatenate Strings • The + operator works even if one of the operands isn’t a String object. The non-String operand is converted to string form automatically: System.out.println("Celsius equivalent: " + celsius);
  • 74. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 74 Using + to Concatenate Strings • If the + operator is used to combine a string with any other kind of object, the object’s toString method is called. • The statement System.out.println("Value of fraction: " + f); has the same effect as System.out.println("Value of fraction: " + f.toString());
  • 75. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 75 Using + to Concatenate Strings • In order for the + operator to mean string concatenation, at least one of its two operands must be a string: System.out.println("Java" + 1 + 2); // Prints "Java12" System.out.println(1 + 2 + "Java"); // Prints "3Java"
  • 76. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 76 Using + to Concatenate Strings • The + operator is useful for breaking up long strings into smaller chunks: System.out.println( "Bothered by unsightly white space? " + "Remove it quickly andneasily with " + "the new, improved trim method!");
  • 77. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 77 Using + to Concatenate Strings • The += operator can be used to add characters to the end of a string: String str = "The quick brown fox "; str += "jumped over "; str += "the lazy dog."; The final value of str will be "The quick brown fox jumped over the lazy dog." • Concatenating a number with an empty string will convert the number to string form. For example, if i contains 37, then i + "" is the string "37".
  • 78. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 78 Program: Decoding a Vehicle Identification Number • The manufacturer of a vehicle assigns it a unique identifying number, called the Vehicle Identification Number (VIN). A VIN packs a large amount of information into a 17-character string:
  • 79. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 79 The Check Digit in a VIN • The check digit in a VIN is computed from the other characters in the VIN; its purpose is to help detect errors. • The check digit algorithm used in vehicle identification numbers will catch most common errors, such as a single incorrect character or a transposition of two characters.
  • 80. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 80 The VIN Program • The VIN program will split a VIN into its constituent pieces. The VIN is entered by the user when prompted: Enter VIN: JHMCB7658LC056658 World manufacturer identifier: JHM Vehicle description section: CB765 Check digit: 8 Vehicle identification section: LC056658
  • 81. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 81 VIN.java // Displays information from a VIN entered by the user import jpb.*; public class VIN { public static void main(String[] args) { // Prompt the user to enter a VIN SimpleIO.prompt("Enter VIN: "); String vin = SimpleIO.readLine(); // Extract the parts of the VIN String manufacturer = vin.substring(0, 3); String description = vin.substring(3, 8); String checkDigit = vin.substring(8, 9); String identification = vin.substring(9);
  • 82. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 82 // Display the parts of the VIN System.out.println("World manufacturer identifier: " + manufacturer); System.out.println("Vehicle description section: " + description); System.out.println("Check digit: " + checkDigit); System.out.println("Vehicle identification section: " + identification); } }
  • 83. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 83 A Condensed Version of the VIN Program VIN2.java // Displays information from a VIN entered by the user import jpb.*; public class VIN2 { public static void main(String[] args) { // Prompt the user to enter a VIN SimpleIO.prompt("Enter VIN: "); String vin = SimpleIO.readLine(); // Display the parts of the VIN System.out.println("World manufacturer identifier: " + vin.substring(0, 3)); System.out.println("Vehicle description section: " + vin.substring(3, 8)); System.out.println("Check digit: " + vin.substring(8, 9)); System.out.println("Vehicle identification section: " + vin.substring(9)); } }
  • 84. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 84 3.10 Case Study: Checking an ISBN Number • An ISBN (International Standard Book Number) is a unique number assigned to a book when it’s published, such as 0–393–96945–2. • The number at the end is a check digit that’s calculated from the other digits in the ISBN. • Our goal is to write a program named CheckISBN that calculates the check digit for an ISBN entered by the user: Enter ISBN: 0-393-96945-2 Check digit entered: 2 Check digit computed: 2
  • 85. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 85 Design of the CheckISBN Program • The CheckISBN program will have four steps: 1. Prompt the user to enter an ISBN. 2. Compute the check digit for the ISBN. 3. Display the check digit entered by the user. 4. Display the computed check digit. • The ISBN will be stored as a string, and the other variables will be integers.
  • 86. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 86 Computing the Check Digit • The check digit is calculated by multiplying the first nine digits in the number by 10, 9, 8, …, 2, respectively, and summing these products to get a value we’ll call total. • The check digit is now determined by the expression 10 – ((total – 1) mod 11) • The value of this expression is a number between 0 and 10. If the value is 10, the check digit is X.
  • 87. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 87 Computing the Check Digit • Computation of the check digit for the ISBN 0– 393–96945–2: total = 0 × 10 + 3 × 9 + 9 × 8 + 3 × 7 + 9 × 6 + 6 × 5 + 9 × 4 + 4 × 3 + 5 × 2 = 0 + 27 + 72 + 21 + 54 + 30 + 36 + 12 + 10 = 262 Check digit: 10 – ((262 – 1) mod 11) = 10 – (261 mod 11) = 10 – 8 = 2
  • 88. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 88 Extracting Digits from the ISBN • In order to compute the check digit, the first nine digits in the ISBN must be extracted and converted to numeric form. • Since the position of the first two dashes may vary, the program will need to search for them. • Once the dashes have been found, the program can extract the language code, publisher, and book number and join these into a single string, the “reduced ISBN.” • If the original ISBN is "0-393-96945-2", the reduced ISBN will be "039396945".
  • 89. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 89 Extracting Digits from the ISBN • Searching for the dashes can be done by calling the indexOf method. • The substring method can extract a portion of the original ISBN. • The + operator can put the pieces together to form the reduced ISBN. • The following expression extracts a digit and converts it to a number: Integer.parseInt(reducedISBN.substring(i, i + 1)) i is the position of the digit in the reduced ISBN.
  • 90. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 90 Displaying the Check Digit • If the check digit is 10, the program will need to display the letter X instead of a normal digit. • This problem can be solved by creating a string containing the digits from 0 to 9, plus the letter X: final String DIGITS = "0123456789X"; • The value of the check digit can be used to select one of the characters in DIGITS. If the check digit is stored in the variable checkDigit, the expression will be DIGITS.charAt(checkDigit)
  • 91. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 91 CheckISBN.java // Program name: CheckISBN // Author: K. N. King // Written: 1998-04-17 // Modified: 1999-02-11 // // Prompts the user to enter an ISBN number. Computes the // check digit for the ISBN. Displays both the check digit // entered by the user and the check digit computed by the // program. import jpb.*; public class CheckISBN { public static void main(String[] args) { // Prompt the user to enter an ISBN SimpleIO.prompt("Enter ISBN: "); String originalISBN = SimpleIO.readLine();
  • 92. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 92 // Determine location of dashes int dashPos1 = originalISBN.indexOf("-"); int dashPos2 = originalISBN.indexOf("-", dashPos1 + 1); // Remove dashes from ISBN String reducedISBN = originalISBN.substring(0, dashPos1) + originalISBN.substring(dashPos1 + 1, dashPos2) + originalISBN.substring(dashPos2 + 1, 11); // Compute the check digit for the ISBN int total = 10 * Integer.parseInt(reducedISBN.substring(0, 1)) + 9 * Integer.parseInt(reducedISBN.substring(1, 2)) + 8 * Integer.parseInt(reducedISBN.substring(2, 3)) + 7 * Integer.parseInt(reducedISBN.substring(3, 4)) + 6 * Integer.parseInt(reducedISBN.substring(4, 5)) + 5 * Integer.parseInt(reducedISBN.substring(5, 6)) + 4 * Integer.parseInt(reducedISBN.substring(6, 7)) + 3 * Integer.parseInt(reducedISBN.substring(7, 8)) + 2 * Integer.parseInt(reducedISBN.substring(8, 9)); int checkDigit = 10 - ((total - 1) % 11);
  • 93. Chapter 3: Classes and Objects JavaJava ProgrammingProgramming FROMTHEBEGINNINGFROMTHEBEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 93 // Display the check digit entered by the user System.out.println("Check digit entered: " + originalISBN.charAt(12)); // Display the computed check digit final String DIGITS = "0123456789X"; System.out.println("Check digit computed: " + DIGITS.charAt(checkDigit)); } }