Java Programming

Download Report

Transcript Java Programming

Java Programming
Classes and Objects Introduced
1
Introduction

A class is a named collection of
Fields, that hold data values.
 Methods, that operate on the fields.

Classes are the most important
reference type (4 others exist)
 Classes define a new datatype

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
2
Simple Class Example

Example:
class Point {
double x; // x coordinate
double y; // y coordinate
}
Defines a 2 dimensional point in Cartesian
coordinates. (No methods yet)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
3
Data types versus data values

It is important to distinguish between
data types and data values:
int is a data type, 42 is a data value of
type int.
 char is a data type, ‘@’ is a character
value (of char type).

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
4
If classes are data types ….

A class is a data type, and data types
define a range of values. So what are the
values of class type?


Objects
An object is an instance of a class. E.g.,
where Point is a class representing all
possible points a Point object
represents a specific point in 2 dims.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
5
Just like blueprints

Classes are like blueprints of a ‘building’.
You cannot live in a ‘building’ blueprint.
 You can use the blueprint to make a specific
‘building’ (or instantiate a ‘building’)
 Every ‘building’ instantiated is its own new
‘building’ and is physically not the same as
the other ‘buildings’


‘not the same’ does not mean they do not look
the same, they are separate buildings.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
6
A Bigger Example
public class Point {
public double x, y;
public Point (double x, double y) {
this.x = x;
this.y = y;
}
public double distanceFromOrigin() {
return Math.sqrt (x*x + y*y);
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
7
A Bigger Example
public class Point {
Name x,
of they;
class is Point
public double
public Point (double x, double y) {
this.x = x;
this.y = y;
}
public double distanceFromOrigin() {
return Math.sqrt (x*x + y*y);
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
8
A Bigger Example
public class Point {
public double x, y;
It has
2 fields named
x and y,x, double y) {
public
Point
(double
both of double type.
this.x = x;
They are public, i.e., directly
this.y
= toy;
available
anyone holding a
reference to an object of type
}
Point.
public double distanceFromOrigin() {
return Math.sqrt (x*x + y*y);
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
9
A Bigger Example
public class Point {
public double x, y;
public Point (double x, double y) {
this.x = x; It has a constructor that takes
this.y = y; in 2 parameters (also called x
and y)
}
public double distanceFromOrigin() {
return Math.sqrt (x*x + y*y);
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
10
A Bigger Example
public class Point {
public double x, y;
public Point (double x, double y) {
this.x = x; this.x refers to the field x, where as x (on the
this.y = y; right hand side of the assignment) is the x from
the parameter list).
}
this is a reference to the object being
public double distanceFromOrigin()
instantiated (almost true ;-), but good {
enough for
now).
return Math.sqrt (x*x + y*y);
We only need this because the field and the
}
parameter is called the same.
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
11
A Bigger Example
public class Point {
public double x, y;
A method
called distanceFromOrigin,
which
public Point
(double
x, double y)
{
takes in no parameters and returns
this.x =
x;
_____
2
this.y √x
=2+y
y;
Math.sqrt is the square root function.
}
public double distanceFromOrigin() {
return Math.sqrt (x*x + y*y);
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
12
What should I call my file?
All classes with the modifier public must
be in separate files that are named the
same as the class.
 For the example, it must be saved in a
file called Point.java


When compiled it generates
Point.class
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
13
Creating Objects

Recall a declaration of an integer variable:
int myInt;
What value does myInt hold?


None, it must be assigned: myInt = 42;
We can declare variable of class type in the
same way:
Point p;
but p do not hold a value until one has been
assigned to it.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
14
Creating Objects

How do we get an object value?
By instantiating a class!
 Use the new keyword.

Point p;
p = new Point (3.14, 2.72);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
15
Instantiating an Object

A number of important things happen
when instantiating an object using new.

An actual object is created based on the
class being instantiated
The object has the fields that the class lists.
 The constructor is executed with the parameters
passed to it (if any).
 An object reference value is returned.

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
16
Types of Fields and Methods

There are 4 types of fields and methods:
Class Fields
 Class Methods
 Instance Fields
 Instance Methods

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
17
Instance Fields

An instance field is a field associated
with an object:
public class Point {
int x;
int y;

Every instance of Point has its own set
of fields x and y.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
18
Class Fields (or static fields)

Where instance of a class (I.e., object)
has instances of instance fields, a class
field is shared between instances:
public class Point {
static int counter = 0;
…
}

We use the word static to denote this.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
19
Public class Point {
int x, y;
static int count = 0;
Point (int x, int y) {
this.x = x;
this.y = y;
count += 1;
}
}
A CLASS
CSC 140 Java Programming
This class field lives here
© Matt B. Pedersen ([email protected])
20
new Point(4,3);
Public class Point {
int x, y;
static int count = 1;
Point (int x, int y) {
this.x = x;
this.y = y;
count += 1;
}
}
A CLASS
CSC 140 Java Programming
x = 4
y = 3
AN OBJECT
• this.x = x initializes the instance field
x to the value of the parameter x (4)
•this.y = y initializes the instance field
y to the value of the parameter y (3)
•count += 1 increments the class field
by one.
© Matt B. Pedersen ([email protected])
21
x = 4
y = 3
new Point(4,3);
Public class Point {
int x, y;
static int count = 2;
Point (int x, int y) {
this.x = x;
this.y = y;
count += 1;
}
new Point(10,98);
}
A CLASS
CSC 140 Java Programming
AN OBJECT
x = 10
y = 98
© Matt B. Pedersen ([email protected])
ANOTHER OBJECT
22
Static fields

A static field can be initialized at declaration
time:
static int count = 0;
 It should never be initialized in a constructor:
Point (int x, int y) {
…
count = 0;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
23
Static Fields

Within the class in which a static field is
declared, it may be referenced by its
name:
public class Point {
static int counter = 0;
int getCouner() { return counter; }
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
24
Field Modifiers
The static modifier makes fields into class
fields.
 Other important modifiers:


public, private, protected


final


Determines if a field can be seen/used outside of the class
in which it is defined.
Once initialized it can never be written to again.
transient, volatile

Don’t worry about these.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
25
Public Static Fields

Public static fields like counter:
public class Point {
public static int counter = 0
…
}
may be referenced like this:

Inside the class: counter (by its name)

Outside the class:


Point.counter (by <class>.<fieldname>)
p.counter, where p is an instance of Point
(<object>.<fieldname>) (This one is not advisable)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
26
Private Static Field

The counter might be private:
public class Point {
private static int counter = 0
…
}
Now, Point.counter is no longer
legal, neither is p.counter.
 Only within Point can counter be
accessed.

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
27
Example
public class Point {
public int x;
public int y;
private static int counter = 0;
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
public static int getInstanceCount() {
return counter;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
28
Example
public class Point {
public int x;
Instance Fields
public int y;
private static int counter = 0;
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
Each object of class Point
instantiated by
new Point(..,..)
as a copy of int x and int y.
public static int getInstanceCount() {
return counter;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
29
Example
public class Point {
public int x;
public int y;
private static int counter = 0;
Class Field
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
Each instance of Point
shares the counter field.
Class fields or static
fields are shared between
instances.
public static int getInstanceCount() {
return counter;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
30
Example
public class Point {
public int x;
public int y;
private static int counter = 0;
Point(int x, int y) {
Constructor
this.x = x;
this.y = y;
A constructor is invoked
counter = counter + 1;
as the first thing that happens
}
at the
new Point(…,…)
public static int getInstanceCount()
call. It{is used to set up fields
return counter;
in the object. new Point(…,…)
}
does not return a reference
}
to the new object until the
constructor has run.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
31
Example
public class Point {
public int x;
public int y;
private static int counter = 0;
Point(int x, int y) {
this.x = x; Object Context
this.y = y;
counter = counter + 1;
}
this is a special reference
value that always referes
to the object that we are
currently operating inside.
Here we use it to get to the
fields as they are overshadowed
by the parameters.
public static int getInstanceCount() {
return counter;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
32
Example
public class Point {
public int x;
public int y;
private static int counter =
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
Since counter is private in Point,
we cannot access it through
Point.counter or
0;
p.counter for any object p of
class Point, so we need a way
to get to the value of counter.
This is called an accessor method..
public static int getInstanceCount()
{ Method
Accessor
return counter;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
33
Example
public class Point {
public int x;
public int y;
private int counter = 0;
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
Point p1 = new Point(1,2);
Point p2 = new Point(3,4);
public static int getInstanceCount()
…
{
return counter;
System.out.println(
}
}
CSC 140 Java Programming
“# of times Point was instantiated:” +
Point.getInstanceCount());
© Matt B. Pedersen ([email protected])
34
Example
public class Point {
public int x;
public int y;
private static int counter = 0;
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
System.out.println(
“# of times Point was instantiated: ” +
Point.getInstanceCount());
System.out.println(p1);
System.out.println(p2);
public static int
getInstanceCount() {
return counter;
}
public String toString() {
return “(“+x+“,”+y+“)”;
}
}
Point p1 = new Point(1,2);
Point p2 = new Point(3,4);
Would produce:
# of times Point was instantiated: 2
(1,2)
(3,4)
Special method called toString; takes no arguments
and returns a String. Automatically called when an
object is used in a print statement.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
35
Example
public class Point {
private int x;
private int y;
private static int counter = 0;
int getX() {
return x; // or this.x
}
int getY() {
return y; // or this.y
}
Point(int x, int y) {
this.x = x;
this.y = y;
counter = counter + 1;
}
public static int
getInstanceCount() {
return counter;
}
void setX(int x) {
this.x = x;
}
void setY(int y) {
this.y = y;
}
}
String toString() {
return “(“+x+“,”+y+“)”;
}
Might be nice to make x and y private as well, but then we need
accessors (also called ‘getters’) for them, and if we want to change
them we need mutators (also called ‘setters’) as well.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
36
Methods

Like fields, we can have

Instance methods (class methods)


Again, we use the static keyword to denote
this.
Object methods (regular methods)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
37
Non-static methods
A regular method (non-static) can be
thought of as ‘belonging to the object’
 It may reference both static and nonstatic fields.
 Can be public, or private, and final


A final method cannot be re-implemented in
subclasses.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
38
Example
public class Circle {
// a class field
public static final double π = 3.14159;
// an instance field
public double r; // the radius of the circle
public Circle(double radius) {
r = radius;
}
public double area() {
return π * r * r;
}
public double circumference () {
return 2 * π * r;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
39
Example
public class Circle {
// a class field
public static final double π = 3.14159;
// an instance field
public double r; // the radius of the circle
public Circle(double radius) {
r = radius;
}
public double area() {
return π * r * r;
}
public double circumference () {
return 2 * π * r;
Can I add this method:
}
public static getRadius() {
}
return r;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
40
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
// Create a circle with radius 5
Circle c1 = new Circle(5);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
41
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
// Create a circle with radius 5
Circle c1 = new Circle(5);
c1 is a reference to an object of class Circle.
A new Circle object is created with the new keyword,
and the value 5 is passed to the constructor.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
42
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
r=5
// Create a circle with radius 5
Circle c1 = new Circle(5);
C1 is a reference to an object of class Circle.
A new Circle object is created with the new keyword,
and the value 5 is passed to the constructor.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
43
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
// Create a circle with radius 5
Circle c1 = new Circle(5);
// Create a circle with radius 20
Circle c2 = new Circle(20);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
r=5
object
r = 100
44
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
// Create a circle with radius 5
Circle c1 = new Circle(5);
// Create a circle with radius 20
Circle c2 = new Circle(20);
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
r=5
object
r = 100
45
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
// Create a circle with radius 5
Circle
c1 = new
Circle(5);
// Create
a circle
with radius 20
Circle c2 = new Circle(20);
System.out.println(c1.area());
double cir = c2.circumference();
double pi = Circle.π;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
r=5
object
r = 100
46
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
c1.area():
public double area() {
return π * r * r;
Value of r from object
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
r=5
47
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
object
c2.circumference():
public double circumference () {
return 2 * π * r;
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
r = 100
48
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
}
double pi = Circle.π;
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
49
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
public static radToDeg(double rads) {
return rads * 180 / π;
}
}
Let us add a class method (a static method)
radsToDeg cannot reference ANY non-static fields!!
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
50
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
public static radToDeg(double rads) {
return rads * 180 / π;
}
}
radsToDeg cannot reference ANY non-static fields!!
Circle.radToDeg(35);
There is no object context for radToDeg to access non-static fields in.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
51
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
public static radToDeg(double rads) {
return rads * 180 / π;
}
}
// Create a
Circle
c1 =
// Create
Circle c2
object
circle with radius 5
new
Circle(5);
a circle
with radius 20
= new Circle(20);
r=5
object
r = 100
How do I get the radius of c1 or c2?
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
52
class
class Circle {
public static final π = 3.14159;
public double r;
public double area() { … }
public double circumference() { … }
public static radToDeg(double rads) {
return rads * 180 / π;
}
}
// Create a
Circle
c1 =
// Create
Circle c2
object
r=5
object
circle with radius 5
new
Circle(5);
a circle
with radius 20
= new Circle(20);
r = 100
raidus in Circle is public, so it can be accessed
Like this: c1.r (= 5) or c2.r (=100) but NOT
Circle.r
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
53
class
object
class Circle {
public static final π = 3.14159;
public double r;
r=5
public double area() { … }
public double circumference() { … }
public static radToDeg(double
rads)
BECAUSE:
r {lives in an object;
return rads * 180 / π;it is not static, and only static
}
fields live in classes and can
}
be accessed through class.field
object
// Create a
Circle
c1 =
// Create
Circle c2
circle with radius 5
new
Circle(5);
a circle
with radius 20
= new Circle(20);
r = 100
raidus in Circle is public, so it can be accessed
Like this: c1.r (= 5) or c2.r (=100) but NOT
Circle.r
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
54

Non-static methods can reference
Non-static fields
 Non-static methods
 Static fields
 Static methods


Static methods can reference
Static fields
 Static methods

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
55
The this keyword

A special keyword ‘this’ can be
referenced inside objects. It refers to the
current context, that is, the object in
which the code is located (NOT class,
but object)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
56
The this keyword
public class Circle {
public static final double π = 3.14159;
private double radius;
public Circle(double radius) {
// set the radius field equal to the radius parameter
}
public double getRadius() { return radius; }
public double area() { return π * radius * radius; }
public double circumference() return 2 * π * radius; }
public static double radToDeg(double rads) {
return rads * 180 / π;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
57
The this keyword
public class Circle {
public static final double π = 3.14159;
private double radius;
public Circle(double radius) {
// set the radius field equal to the radius parameter
}
Problem: both the field and the
public double
getRadius()
{ radius.
return radius; }
parameter
is called
public double area() { return π * radius * radius; }
public double circumference() return 2 * π * radius; }
public static double radToDeg(double rads) {
return rads * 180 / π;
}
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
58
The this keyword
public class Circle {
public static final double π = 3.14159;
private double radius;
public Circle(double radius) {
// set the radius field equal to the radius parameter
}
Problem: both the field and the
public double
getRadius()
{ radius.
return radius; }
parameter
is called
public double area() { return π * radius * radius; }
Solution: The fieldreturn
can be2referenced
like any}
public double circumference()
* π * radius;
other public
field by:
public static double
radToDeg(double
rads) {
objectRef.fieldName
return rads * 180 / π;
But we don’t have an object reference do we?
}
Yes we do, it is called ‘this’
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
59
The this keyword
public class Circle {
public static final double π = 3.14159;
private double radius;
public Circle(double radius) {
this.radius = radius;
}
Problem: both the field and the
public double
getRadius()
{ radius.
return radius; }
parameter
is called
public double area() { return π * radius * radius; }
Solution: The fieldreturn
can be2referenced
like any}
public double circumference()
* π * radius;
other public
field by:
public static double
radToDeg(double
rads) {
objectRef.fieldName
return rads * 180 / π;
But we don’t have an object reference do we?
}
Yes we do, it is called ‘this’
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
60
Copying an Object

Consider this code:
Circle c1 = new Circle(20);
Circle c2 = c1;
c1 and c2 are references to the same object!
There is no built-in way to clone an object, so we need to make one:
public Circle clone() {
return new Circle(radius);
}
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
61
Multiple Constructors

With the Circle class we must provide an
initial radius when instantiating the class:
Circle c1 = new Circle(4);

What about
Circle c2 = new Circle();

That is illegal, there is no constructor
with no arguments.
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
62
Multiple Constructors

Lets make one then, but what value
should radius have?
public Circle() {
this.radius = 1; // we pick 1
}

This does the same as calling the other
constructor with the value 1!
Public Circle() {
this(1);
}

This is called an explicit constructor
invocation. (Must appear on line 1)
CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
63
Inheritance
Let us start by an example.
 A “vehicle” can be a car, a truck, a motor
cycle, a bike, a scooter etc. What do all
those things have in common?

Wheels
 Color
 ….

CSC 140 Java Programming
© Matt B. Pedersen ([email protected])
64
Inheritance

Let us design a class for a vehicle:
public class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
Inheritance

We can break the list of all vehicles into
the motorized ones and the ‘manual’
ones; we could draw a diagram like this:
Vehicle
MotorizedVehicle

ManualVehicle
All motorized vehicles are vehicles, and
all manual vehicles are vehicles.
Inheritance

We could define separate classes for
MotorizedVehicle and ManualVehicle:
public class MotorizedVehicle {
private int wheels;
private String color;
private int cc;
public class ManualVehicle {
private int wheels;
private String color;
private boolean hasSeat;
public MotorizedVehicle(
int wheels,
String color, int cc) {
this.wheels = wheels;
this.color = color;
this.cc = cc;
}
…
}
public ManualVehicle(int wheels,
String color,
boolean hasSeat) {
this.wheels = wheels;
this.color = color;
this.hasSeat = hasSeat;
}
…
}
Inheritance

We could define separate classes for
MotorizedVehicle and ManualVehicle:
public class MotorizedVehicle {
private int wheels;
private String color;
private int cc;
public class ManualVehicle {
private int wheels;
private String color;
private boolean hasSeat;
public MotorizedVehicle(
public ManualVehicle(int wheels,
int wheels,
String color,
Both classes have
String color, int cc) {
boolean hasSeat) {
These
fields,
this.wheels = wheels;
this.wheels = wheels;
BECAUSE
they
are
this.color = color;
this.color = color;
this.cc = cc;
this.hasSeat = hasSeat;
both Vehicles.
}
}
…
…
}
}
Inheritance

We could define separate classes for
MotorizedVehicle and ManualVehicle:
public class MotorizedVehicle {
public class ManualVehicle {
private int wheels;
private int wheels;
private String Both
color;
private
String color;
constructors execute
partially
private int cc;the same code; The initialization
private boolean hasSeat;
Of the fields they have inpublic
common
public MotorizedVehicle(
ManualVehicle(int wheels,
look alike.
int wheels,
String color,
String color, int cc) {
boolean hasSeat) {
this.wheels = wheels;
this.wheels = wheels;
this.color = color;
this.color = color;
this.cc = cc;
this.hasSeat = hasSeat;
}
}
…
…
}
}
Inheritance

Perhaps we could redraw the picture
from before:
Vehicle

We can imagine a
MotorizedVehicle
Vehicle
MotorizedVehicle
Vehicle
ManualVehicle
consisting of a
Vehicle plus
some new stuff.
Inheritance
public class MotorizedVehicle extends Vehicle {
private int cc;
public MotorizedVehicle(
int wheels,
String color, int cc) {
super(wheels, color);
this.cc = cc;
}
public getCc() {
public class Vehicle {
return cc;
private int wheels;
}
}
private String colour;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
Inheritance
public class MotorizedVehicle extends Vehicle {
private int cc;
public MotorizedVehicle(
int wheels,
inherit
the fields and methods
String color, intTo
cc)
{
super(wheels, color); from the super class we use the
this.cc = cc;
keyword extends.
}
public getCc() {
public class Vehicle {
return cc;
private int wheels;
}
}
private String colour;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
Inheritance
public class MotorizedVehicle extends Vehicle {
A super class’
private int cc;
constructor must be
executed as well. Either explicitly
using the keyword super, or implicitly
{(by not putting anything, in which
case the default constructor of
the super class gets called)
public MotorizedVehicle(
int wheels,
String color, int cc)
super(wheels, color);
this.cc = cc;
}
public getCc() {
public class Vehicle {
return cc;
private int wheels;
}
}
private String colour;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
Inheritance

What happens when we do:
MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
Inheritance

What happens when we do:

MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
Object for a MotorizedVehicle is created.
MotorizedVehicle
object
int cc
Inheritance

What happens when we do:

MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);
Object for a MotorizedVehicle is created.
Object for Vehicle is created.

MotorizedVehicle
object
int cc
Vehicle
object
int wheels
String color
Inheritance





What happens when we do:
MotorozedVehicle mv = new MotorizedVehicle(4,”Red”,4000);
Object for a MotorizedVehicle is created.
Object for Vehicle is created.
MotorizedVehicle
Constructor for Vehicle
is executed through
Vehicle
object
super(4,”Red”)
object
Rest of the constrctor
for MotorizedVehicle
is executed.
int cc
4000
int wheels 4
String color “Red”
Inheritance

Since mv is a MotorizedVehicle that
inherits for Vehicle, all of the following
are legal:
mv.getwheels();
 mv.getColor();
 mv.getCc();


But only public methods may be invoked
from outside the object.
Inheritance

In addition, if Vehicle has a private
method, then it cannot be invoked from
MotorizedVehicle.
public class A {
private void foo() { … }
}
public class B extends A {
public void bar() {
foo(); // illegal invocation
}
}
Inheritance
A class can only inherit from one other
class. If it doesn’t inherit from any class,
by default java/lang/Object is its
super class.
 All public method and fields are inherited.
 Private fields and methods are not.
 Explicit constructor calls (super(..))
may only be to public constructors in the
super class.

The Abstract Modifier

The modifier abstract can be used
on classes and methods.
 An abstract method has no body:
public abstract void foo(int x) ;
abstract class may have
abstract methods, and a class that
has abstract methods must be
abstract
 An
The Abstract Modifier
Abstract classes cannot be instantiated
 What would happen if you
instantiated a class with an abstract
method?
 A subclass of an abstract class
must also be abstract unless it
implements all un-implemented
abstract methods in its class
hierarchy.

The Abstract Modifier

Example: recall this code:
public class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}

We might not want to allow a Vehicle
to be instantiated.
The Abstract Modifier
public abstract class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
Though this class has no abstract
methods.
 Maybe each vehicle sub-type has a
specific string identifying it.

The Abstract Modifier
public abstract class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
}
A Car’s sub-type string is “car”, a motor
cycle’s sub-type string is “motor cycle”.
 We need a method called getType()

The Abstract Modifier
public abstract class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
public String getType() { return ????????; }
}

What should we return for a Vehicle?
 Nothing - a vehicle doesn’t have a
type, but we must make sure all sub
classes of Vehicle do.
The Abstract Modifier
public abstract class Vehicle {
private int wheels;
private String color;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
public abstract String getType() ;
}

Now all subsclasses must implement
getType()
The Abstract Modifier
 We
can no longer do:
new Vehicle(…);
 What about the immediate subclass
MotorizedVehicle? Should it be
abstract? It depends
Yes, if you don’t want instances of it
No, if you want instances of it
The Abstract Modifier
public abstract class MotorizedVehicle extends Vehicle {
private int cc;
public MotorizedVehicle(
int wheels,
String color, int cc) {
super(wheels, color);
this.cc = cc;
}
public abstract String getType() ;
public getCc() {
return cc;
}
}
public abstract class Vehicle {
private int wheels;
private String colour;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
public abstract String getType() ;
}
The Abstract Modifier
public class Car extends MotorizedVehicle {
// fields for a car
public Car(int wheels, String color, int cc, …………… ) {
super(wheels,color,cc);
// set the extra fields
public abstract class MotorizedVehicle extends Vehicle
}
private int cc;
// additional accessors
public MotorizedVehicle(
public String getType() {
int wheels,
String color, int cc) {
return “Car”;
super(wheels, color);
this.cc = cc;
}
}
public abstract String getType() ;
}
public getCc() {
return cc;
}
}
{
public abstract class Vehicle {
private int wheels;
private String colour;
public Vehicle(int wheels, String color) {
this.wheels = wheels;
this.color = color;
}
public int getWheels() { return wheels; }
public String getColor() { return color; }
public abstract String getType() ;
}
The Abstract Modifier
public class Arraylist<E> {
private E[] elements;
private int index, size;
public int size() {
return index;
}
public Arraylist() {
elements =(E[]) new Object[5];
index = 0;
size = 5;
}
public Arraylist(E[] es) {
elements = es;
size = index = es.length;
}
public E get(int index) {
return elements[index];
}
public E[] toArray(E[] es) {
for (int i=0;i<index;i++)
es[i]=elements[i];
return es;
}
}
public void add(E element) {
if (index < size-1)
elements[index++] = element;
else {
E[] newElements = (E[])
new Object[size * 2];
for (int i=0;i<index;i++)
newElements[i] =
elements[i];
size = size * 2;
elements = newElements;
}
}
What information from this class
must we know about to use the
class?
The Abstract Modifier

From the Account2.java file where we
use Arraylist
private Arraylist<Transaction> transactions;
transactions = new Arraylist<Transaction>();
transactions.add(t);
Transaction t[] = transactions.toArray(new
Transaction[transactions.size()]);
transactions = new Arraylist<Transaction>(t);
The Abstract Modifier
public class Arraylist<E> {
// some internal representation of fields.
public
public
public
public
public
public
Arraylist() { … }
Arraylist(E[] es) { … }
void add(E element) { … }
int size() { … }
E get(int index) { … }
E[] toArray(E[] es) { … }
}
We don’t really care about the implementation or the internal representation,
just about the public methods. (Though we do care about the constructors in
Arraylist.
For the code in Account2.java all we care about is that those methods above
are available. For all we care, any old data structure with those methods
could be used.
The Interface
We are really only interested in the
interface of the implementing class.
 As long as the class promises to make
available the methods we need we don’t
care about the implementation.
 We could set up a new class hierarchy
where Arraylist inherits from some
completely abstract Collection class
and use it in the Account2 class

The Interface
public class Account2 {
private Collection<Transaction> transactions;
private double balance;
private String name;
private String street;
private int zip;
private String state;
private String city;
public Account2(String name, String street, int zip,
String state, String city) {
transactions = new Arraylist<Transaction>();
balance = 0;
this.name = name;
this.street = street;
this.state = state;
this.zip = zip;
this.city = city;
}
public void deposit(Date date, String text, double amount) {
Transaction t = new Transaction(date, text, amount);
transactions.add(t);
balance += amount;
}
. . . .
}
The Interface
public class Account2 {
private Collection<Transaction> transactions;
private double balance;
private String name;
private String street;
private int zip;
private String state;
private String city;
public Account2(String name, String street, int zip,
String state, String city) {
transactions = new Arraylist<Transaction>();
balance = 0;
this.name = name;
this.street = street;
public class Arraylist<E> extends Collection<E>
this.state = state;
{
this.zip = zip;
this.city = city;
// implement everything in Collection
}
}
public void deposit(Date date,
public
String
abstract
text,
class
double
Collection<E>
amount) { {
Transaction t = new Transaction(date,
public void add(E
text,element)
amount);;
transactions.add(t);
public int size() ;
balance += amount;
public E get(int index);
}
public E[] toArray(E[] es);
}
. . . .
}
Interfaces
public class Account2 {
private Collection<Transaction> transactions;
private double balance;
private String name;
private String street;
private int zip;
private String state;
private String city;
Classes 100% abstract are really
not classes but interfaces, and
public Account2(String name, String street, int zip,
String state, String city)
{
should
be declared in an interface
transactions = new Arraylist<Transaction>();
balance = 0;
rather than a class.
this.name = name;
this.street = street;
public class Arraylist<E> implements
this.state = state;
Collection<E> {
this.zip = zip;
this.city = city;
// implement everything in Collection
}
}
public void deposit(Date date,
public
String
interface
text,Collection<E>
double amount)
{ {
Transaction t = new Transaction(date,
public void add(E
text,element)
amount);;
transactions.add(t);
public int size() ;
balance += amount;
public E get(int index);
}
public E[] toArray(E[] es);
}
. . . .
}
Interfaces
Interfaces cannot be instantiated (for the
same reason abstract classes cannot)
 An interface is a contract, it tell you what
methods a class must implement if it
‘implements’ the interface.
 Variables can be of interface type.

Multiple inheritance

A class can only inherit from one super class:
public class A extends B,C
Is illegal.
 A class can implement multiple interfaces:
public class A implements D,E
 A class can implement and extend at the same time:
public class A extends B implements D,E
Multiple inheritance

Why is multiple inheritance not a good thing:
public class A {
public String foo() {
return “foo”;
}
}
public class B {
public String foo() {
return “bar”;
}
}
public class C extends A,B {
// which foo method does C inherit?
}