ch01_modified
ch01_modified
Structures and
Algorithms
Object-Oriented Programming and Class
Hierarchies
Objectives
Abstract classes
Abstract data types
How Java determines which method to execute
when there are multiple methods
Object class and overriding Object class
methods
Exception hierarchy
Covered by the TA in the lab.
Checked and unchecked exceptions
Covered by the TA in the lab.
Packages and visibility
Briefly covered.
Introduction to Object-
Oriented Programming
CIS 2168 Data Structures and
Algorithms
ADTs
Abstract Date Type
(ADT)
An encapsulation of
data and methods
Allows for reusable
code
The user need not
know about the
implementation of the
ADT
A user interacts with
the ADT using only
public methods
ADTs (cont.)
ADTs facilitate storage, organization,
and processing of information
Such ADTs often are called data
structures
The Java Collections Framework
provides implementations of common
? ??
data structures
?
Object-Oriented
Programming
Object-oriented programming (OOP) is
popular because:
it enables reuse of previous code saved as
classes
which saves times because previously
written code has been tested and
debugged already
If a new class is similar to an existing
class, the existing class can be extended
This extension of an existing class is
called inheritance
Inheritance
A Human is a
Mammal
Human has all the
data fields and
methods defined by
Mammal
Mammal is the
superclass of Human
Human is a subclass
of Mammal
Human may define
other variables and
methods that are not
contained in Mammal
Inheritance (cont.)
Mammal has only
method
drinkMothersMilk()
Human has method
drinkMothersMilk() and
thinkCreatively()
Objects lower in the
hierarchy are
generally more
powerful than their
superclasses because
of additional attributes
A Superclass and Subclass
Example
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
Initialization (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; Construc
diskSize = disk;
processorSpeed = procSpeed;
tor
}
A Superclass and Subclass
Initialization (cont.)
/** Class that represents a computers */ Use of this
public class Computer {
// Data fields
private String manufacturer; If you wrote this line as
private String processor;
private double ramSize; Same name, processor = processor;
private int diskSize;
different
private double processorSpeed;
variables
you would simply copy the
// Methods
/** Initializes a Computer object with all properties specified. variable processor to itself.
@param man The computer manufacturer To access the field, you need
@param processor The processor type
@param ram The RAM size
to prefix this:
@param disk The disk size
@param procSpeed The processor speed this.processor = processor;
*/
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.)
public double computePower() { return ramSize * processorSpeed; }
public double getRamSize() { return ramSize; }
public double getProcessorSpeed() { return processorSpeed; }
public int getDiskSize() { return diskSize; }
// insert other accessor and modifier methods here
. . .
}
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);
super()
screenSize = screen; super(argumentList)
weight = wei;
The super()call in a class constructor invokes the
} superclass’s constructor that has the
corresponding argumentList.
class SuperClass
{
String s;
public SuperClass(String s)
{
this.s = s;
}
}
public SubClass(String s)
{
System.out.println("Sub");
}
If a Notebook extends
Computer,then the
Notebook is-a Computer
Method Overriding,
Method Overloading, and
Polymorphism
Job Interview Question
What is polymorphism? Give an
example.
}
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
Using toString()
the prefix super in a call
method will override
to a method its
methodName calls
Computer's
the method toString()
with that nameandin will
bethe superclass
called for all of the current
Notebook objects.
class
Method Overloading
Override versus Overload
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) {
. . .
}
In Steerable.java:
[...]
myFleet[i].start();
anotherFleet[i].turnLeft(100);
anotherFleet[i+1].turnRight(45);
Abstract Classes Versus Interfaces
When should one use an Abstract class instead of an
interface?
If the subclass-superclass relationship is genuinely an "is a"
relationship.
If the abstract class can provide an implementation at the
appropriate level of abstraction
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
}
The try-catch Sequence
(cont.)
The try-catch sequence resembles an if-then-else
PITFALL!
statement Unreachable catch 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 the 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
Briefly covered.
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
So… use the most restrictive visibility possible
to get the job done!
Do not confuse visibility and inheritance:
private members are inherited, though not
directly accessible