Ch01-Java Review
Ch01-Java Review
Interface Code
___
An automated teller machine public interface ATM {
(ATM) enables a user to perform
certain banking operations from }
a remote location. It must support
the following operations:
verify a user's Personal
Identification Number (PIN)
allow the user to choose a
particular account
Withdraw a specified amount of
money
display the result of an operation
display an account balance
Example: ATM Interface (cont.)
Interface Code
___
An automated teller machine public interface ATM {
(ATM) enables a user to perform
certain banking operations from }
a remote location. It must support
the following operations:
verify a user's Personal
Identification Number (PIN) The keyword interface in
allow the user to choose a the header indicates that an
particular account interface is being declared
withdraw a specified amount of
money
display the result of an operation
display an account balance
Example: ATM Interface (cont.)
Interface Code
___
An automated teller machine public interface ATM {
(ATM) enables a user to perform
certain banking operations from /** Verifies a user's PIN.
a remote location. It must support
@param pin The user's PIN
the following operations:
verify a user's Personal */
Identification Number (PIN) boolean verifyPIN(String pin);
allow the user to choose a }
particular account
withdraw a specified amount of
money
display the result of an operation
display an account balance
Example: ATM Interface (cont.)
Interface Code
___
An automated teller machine public interface ATM {
Interface Code
___
An automated teller machine /** Withdraws a specified amount
of money
(ATM) enables a user to perform
@param account The account
certain banking operations from from which the money
a remote location. It must support comes
the following operations: @param amount The amount of
verify a user's Personal money withdrawn
Identification Number (PIN) @return whether or not the
operation is
allow the user to choose a successful
particular account
*/
withdraw a specified amount of boolean withdraw(String account,
money double amount);
display the result of an operation.
display an account balance }
Example: ATM Interface (cont.)
Interface Code
___
An automated teller machine /** Displays the result of an
operation
(ATM) enables a user to perform
certain banking operations from @param account The account
from which money was
a remote location. It must support withdrawn
the following operations: @param amount The amount of
verify a user's Personal money withdrawn
Identification Number (PIN) @param success Whether or
allow the user to choose a not
particular account the withdrawal took
place
withdraw a specified amount of
money */
display the result of an operation void display(String account,
double amount,
display an account balance boolean success);
Example: ATM Interface (cont.)
Interface Code
___
An automated teller machine /** Displays an account balance
(ATM) enables a user to perform @param account The account
certain banking operations from selected
a remote location. It must support */
the following operations: void showBalance(String
verify a user's Personal account);
Identification Number (PIN)
allow the user to choose a
particular account
withdraw a specified amount of
money
display the result of an operation.
display an account balance
Interfaces (cont.)
The interface definition shows only headings for its
methods
Because only headings are shown, they are
considered abstract methods
Each abstract method must be defined in a class
that implements the interface
Interface Definition
FORM: Constants are defined in
the interface
public interface interfaceName { DEDUCTIONS are
abstract method headings accessible in classes that
constant declarations implement the interface
}
EXAMPLE:
/* interface type */
ATM ATM1 = new ATMBankAmerica();
ATM ATM2 = new ATMforAllBanks();
Computer
A computer has a
manufacturer
processor
RAM
disk
A Superclass and Subclass Example
(cont.)
Computer
A computer has
manufacturer
processor
RAM Computer
disk String manufacturer
String processor
int ramSize
int diskSize
double processorSpeed
A Superclass and Subclass Example
(cont.)
Computer
String manufacturer
String processor
int ramSize
int diskSize
double processorSpeed
int getRamSize()
int getDiskSize()
double getProcessorSpeed()
Double computePower()
String toString()
A Superclass and Subclass Example
(cont.)
Notebook
A Notebook has all the properties
of Computer,
manufacturer
processor
RAM
Disk
plus,
screen size
weight
A Superclass and Subclass Example
(cont.)
Computer
String manufacturer
String processor
int ramSize
int diskSize
double processorSpeed
int getRamSize()
int getDiskSize()
double getProcessorSpeed()
Double computePower()
String toString() Notebook
double screenSize
double weight
A Superclass and Subclass Example
(cont.)
The constructor of a subclass begins by initializing
the data fields inherited from the superclass(es)
super(man, proc, ram, disk, procSpeed);
// Methods
/** Initializes a Computer object with all properties specified.
@param man The computer manufacturer
@param processor The processor type
@param ram The RAM size
@param disk The disk size
@param procSpeed The processor speed
*/
public Computer(String man, String processor, double ram, int disk,
double procSpeed) {
manufactuer = man;
this.processor = processor;
ramSize = ram;
diskSize = disk;
processorSpeed = procSpeed;
}
A Superclass and Subclass Example
(cont.)
/** Class that represents a computers */
public class Computer { Use of this
// Data fields
private String manufacturer;
private String processor;
If you wrote this line as
private double ramSize;
private int diskSize; processor = processor;
private double processorSpeed;
. . .
}
A Superclass and Subclass Example
(cont.)
// methods
//* Initializes a Notebook object with all properties specified.
@param man The computer manufacturer
@param processor The processor type
@param ram The RAM size
@param disk The disk size
@param procSpeed The processor speed
@param screen The screen size
@param wei The weight
*/
public Notebook(String man, String processor, double ram, int disk,
double procSpeed, double screen, double wei) {
super(man, proc, ram, disk, procSpeed);
screenSize = screen;
weight = wei;
}
A Superclass and Subclass Example
(cont.)
// methods
//* Initializes a Notebook object with all properties specified.
@param man The computer manufacturer
@param processor The processor type
@param ram The RAM size
@param disk The disk size
@param procSpeed The processor speed
@param screen The screen size
@param wei The weight
*/
public Notebook(String man, String processor, double ram, int disk,
double procSpeed, double screen, double wei) {
super(man, proc, ram, disk, procSpeed);
screenSize = screen; super()
weight = wei; super(argumentList)
}
The super()call in a class constructor invokes the superclass’s
constructor that has the corresponding argumentList.
If a Notebook extends
Computer,then the
Notebook is-a Computer
_____ Overriding,
Method _________ _____
Method Overloading,
and Polymorphism
__________ ___ ___________
Section 1.3
Method Overriding
Continuing the previous
example, if we declare and
then run:
}
Now Notebook's toString() method
will override Computer's inherited
toString()method and will be called
for all Notebook objects
Method Overriding (cont.)
To define a toString() for
Notebook:
public String toString() {
String = result = super.toString() +
"\nScreen size: " +
screenSize + " inches" +
"\nWeight: " + weight +
" pounds";
return result;
} super.methodName()
Now Notebook's toString() method
willUsing the prefix
override super in a call to a
its Computer's
method methodName calls the method
toString() and will be called for all
with that name in the superclass of the
Notebook
current class
objects.
Method Overloading (cont.)
Methods in the class hierarchy which have the same
name, return type, and parameters override
corresponding inherited methods
Methods with the same name but different
parameters are overloaded
Method Overloading (cont.)
Take, for example, our Notebook constructor:
public Notebook(String man, String processor, double ram, int disk,
double procSpeed, double screen, double wei) {
. . .
}
If we want to have
This callainvokes
default manufacturer for a
the seven-parameter
constructor passing on the six parameters in
Notebook, we can create a constructor with six
this constructor, plus the default manufacturer
parameters instead of DEFAULT_NB_MAN
constant seven
public Notebook(String processor, double ram, int disk,
double procSpeed, double screen, double wei) {
this(DEFAULT_NB_MAN, double ram, int disk, double procSpeed,
double screen, double wei);
}
Method Overloading: Pitfall
When overriding a method, the method must have the
same name and the same number and types of
parameters in the same order
If not, the method will overload
This error is common; the annotation @Override
preceding an overridden method will signal the complier
to issue an error if it does not find a corresponding
method to override
@Override
public String toString() {
. . .
}
It is good programming practice to use the
@Override annotation in your code
Polymorphism
Polymorphism means having many shapes
Polymorphism is a central feature of OOP
It enables the JVM to determine at run time which
of the classes in a hierarchy is referenced by a
superclass variable or parameter
Polymorphism (cont.)
For example, if you write a program to reference
computers, you may want a variable to reference a
Computer or a Notebook
If you declare the reference variable as
Computer theComputer; it can reference either a
Computer or a Notebook—because a Notebook
is-a Computer
Polymorphism (cont.)
Suppose the following statements
are executed
theComputer = new Notebook("Bravo",
"Intel", 4, 240, 2/4, 15.07.5);
System.out.println(theComputer.toString());
Example: ArrayBasedPD@ef08879
The name of the class, @, instance’s hash code
Operations Determined by Type of
Reference Variable
As shown previously with Computer and Notebook,
a variable can refer to object whose type is a subclass
of the variable’s declared type
Java is strongly typed
Object athing = new Integer(25);
The compiler always verifies that a variable’s type includes
the class of every expression assigned to the variable (e.g.,
class Object must include class Integer)
Operations Determined by Type of
Reference Variable (cont.)
The type of the variable determines what operations are
legal
Object athing = new Integer(25);
The following is legal:
athing.toString();
But this is not legal:
athing.intValue();
Object has a toString() method, but it does
not have an intValue() method (even though
Integer does, the reference is considered of type
Object)
Operations Determined by Type of
Reference Variable (cont.)
The following method will compile,
athing.equals(new Integer("25"));
Incompatible types!
Casting in a Class Hierarchy
Casting obtains a reference of a different, but matching,
type
Casting does not change the object!
It creates an anonymous reference to the object
Downcast:
Cast superclass type to subclass type
Java checks at run time to make sure it’s legal
If it’s not legal, it throws ClassCastException
Using instanceof to Guard a
Casting Operation
• instanceof can guard against a
ClassCastException
// Non OO style:
if (stuff[i] instanceof Integer)
sum += ((Integer) stuff[i]).doubleValue();
else if (stuff[i] instanceof Double)
sum += ((Double) stuff[i]).doubleValue();
...
// OO style:
sum += stuff[i].doubleValue();
Polymorphism Eliminates Nested if
Statements (cont.)
Polymorphic code style is more extensible; it works
automatically with new subclasses
Polymorphic code is more efficient; the system does
one indirect branch versus many tests
So ... uses of instanceof may suggest poor
coding style
Method Object.equals
Object.equals method has a parameter of
type Object
public boolean equals (Object other) {
... }
Compares two objects to determine if they are
equal
A class must override equals in order to support
comparison
Employee.equals()
/** Determines whether the current object matches its argument.
@param obj The object to be compared to the current object
@return true if the objects have the same name and address;
otherwise, return false
*/
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null) return false;
if (this.getClass() == obj.getClass()) {
Employee other = (Employee) obj;
return name.equals(other.name) &&
address.equals(other.address);
} else {
return false;
}
}
Class Class
Every class has a Class object that is created
automatically when the class is loaded into an
application
Each Class object is unique for the class
Method getClass()is a member of Object that
returns a reference to this unique object
In the previous example, if this.getClass() ==
obj.getClass() is true, then we know that obj and
this are both of class Employee
A Java Inheritance Example—The Exception
Class Hierarchy
Section 1.6
Run-time Errors or Exceptions
Run-time errors
occur during program execution (i.e. at run-time)
occur when the JVM detects an operation that it knows
to be incorrect
cause the JVM to throw an exception
Checked exceptions
normally not due to programmer error
generally beyond the control of the programmer
all input/output errors are checked exceptions
Examples: IOException, FileNotFoundException
}
The try-catch Sequence (cont.)
The try-catch sequence resembles an if-then-else statement
PITFALL!
try { Unreachable catch block
// Execute the following statements until an
// exception is thrown ExceptionTypeB cannot be a
...
// Skip the catch blocks if no exceptionssubclass of ExceptionTypeA.
were thrown If
is was, its exceptions would be
} catch (ExceptionTypeA ex) { caught be the first catch clause
// Execute this catch block if an exception of type
and its catch clause would be
// ExceptionTypeA was thrown in the try block
... unreachable.
} catch (ExceptionTypeB ex) {
// Execute this catch block if an exception of type
// ExceptionTypeB was thrown in the try block
...
}
Using try-catch
User input is a common source of exceptions
public static int getIntValue(Scanner scan) {
int nextInt = 0; // next int value
boolean validInt = false; // flag for valid input
while(!validInt) {
try {
System.out.println("Enter number of kids: ");
nextInt = scan.nextInt();
validInt = true;
} catch (InputMismatchException ex) {
scan.nextLine(); // clear buffer
System.out.println("Bad data-enter an integer");
}
}
return nextInt;
}
Throwing an Exception When
Recovery is Not Obvious
In some cases, you may be able to write code that
detects certain types of errors, but there may not
be an obvious way to recover from them
In these cases an exception can be thrown
The calling method receives the thrown exception
and must handle it
Throwing an Exception When
Recovery is Not Obvious (cont.)
public static void processPositiveInteger(int n) {
if (n < 0) {
throw new IllegalArgumentException(
"Invalid negative argument");
} else {
// Process n as required
...
}
}
Throwing an Exception When
Recovery is Not Obvious (cont.)
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
int num = getIntValue(scan);
processPositiveInteger(num);
} catch (IllegalArguementException ex) {
System.err.println(ex.getMessage());
System.exit(1); // error indication
}
System.exit(0); // normal exit
}
Packages and Visibility
Section 1.7
Packages
A Java package is a group of cooperating classes
The Java API is organized as packages
Indicate the package of a class at the top of the file:
package classPackage;
Classes in the same package should be in the same
directory (folder)
The folder must have the same name as the package
Classes in the same folder must be in the same
package
Packages and Visibility
Classes not part of a package can only access public
members of classes in the package
If a class is not part of the package, it must access the
public classes by their complete name, which would
be packagename.className
For example,
x = Java.awt.Color.GREEN;
If the package is imported, the packageName prefix is
not required.
import java.awt.Color;
...
x = Color.GREEN;
The Default Package
Files which do not specify a package are part of
the default package
If you do not declare packages, all of your classes
belong to the default package
The default package is intended for use during the
early stages of implementation or for small
prototypes
When you develop an application, declare its
classes to be in the same package
Visibility
You know about three visibility layers, public, protected,
private
A fourth layer, package visibility, lies between private and
protected
Classes, data fields, and methods with package visibility are
accessible to all other methods of the same package, but are
not accessible to methods outside the package
Classes, data fields, and methods that are declared protected
are visible within subclasses that are declared outside the
package (in addition to being visible to all members inside the
package)
There is no keyword to indicate package visibility
Package visibility is the default in a package if public,
protected, private are not used
Visibility Supports Encapsulation
Visibility rules enforce encapsulation in Java
private: for members that should be invisible even
in subclasses
package: shields classes and members from classes
outside the package
protected: provides visibility to extenders of
classes in the package
public: provides visibility to all
Visibility Supports Encapsulation
(cont.)
Visibility Supports Encapsulation
(cont.)
Encapsulation insulates against change
Greater visibility means less encapsulation