Download Java Programming

Document related concepts
no text concepts found
Transcript
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