a class java programmingmatt/teaching/csc140/chapter3-4up.pdfcsc 140 java programming © matt b....

25
1 Java Programming Classes and Objects Introduced CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 2 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]) 3 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]) 4 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).

Upload: others

Post on 16-Jul-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

1

Java Programming

Classes and Objects Introduced

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 2

Introduction

! A class is a named collection of! Fields, that hold data values.! Methods, that operate on the fields.

! Classes are the most importantreference type (4 others exist)

! Classes define a new datatype

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 3

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]) 4

Data types versus data values

! It is important to distinguish betweendata 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).

Page 2: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 5

If classes are data types ….

! A class is a data type, and data typesdefine a range of values. So what arethe values of class type?! Objects

! An object is an instance of a class. E.g.,where Point is a class representing allpossible points a Point objectrepresents a specific point in 2 dims.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 6

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 asthe 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]) 7

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]) 8

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); }}

Name of the class is Point

Page 3: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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; this.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}

It has 2 fields named x andy, both of double type.

They are public, i.e., directlyavailable to anyone holding areference to an object of typePoint.

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.y = y; } public double distanceFromOrigin() { return Math.sqrt (x*x + y*y); }}

It has a constructor thattakes in 2 parameters (alsocalled x and y)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 11

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); }}

this.x refers to the field x, where as x (on theright hand side of the assignment) is the x fromthe parameter list).

this is a reference to the object beinginstantiated (almost true ;-), but good enoughfor now).

We only need this because the field and theparameter is called the same.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 12

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); }}

A method called distanceFromOrigin, whichtakes in no parameters and returns _____!x2+y2

Math.sqrt is the square root function.

Page 4: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 13

What should I call my file?

! All classes with the modifier public mustbe in separate files that are named thesame as the class.

! For the example, it must be saved in afile called Point.java

! When compiled it generatesPoint.class

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 14

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 thesame way: Point p;but p do not hold a value until one has beenassigned to it.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 15

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]) 16

Instantiating an Object

! A number of important things happenwhen 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.

Page 5: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 17

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]) 18

Instance Fields

! An instance field is a field associatedwith 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]) 19

Class Fields (or static fields)

! Where instance of a class (I.e., object)has instances of instance fields, a classfield 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]) 20

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

This class field lives here

Page 6: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 21

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

x = 4y = 3new Point(4,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.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 22

Public class Point { int x, y; static int count = 2; Point (int x, int y) { this.x = x; this.y = y; count += 1; }} A CLASS

x = 4y = 3new Point(4,3);

AN OBJECT

x = 10y = 98

new Point(10,98);

ANOTHER OBJECT

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 23

Static fields

! A static field can be initialized at declarationtime: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]) 24

Static Fields

! Within the class in which a static field isdeclared, it may be referenced by itsname:public class Point { static int counter = 0; int getCouner() { return counter; }

}

Page 7: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 25

Field Modifiers

! The static modifier makes fields into classfields.

! Other important modifiers:! public, private, protected

! Determines if a field can be seen/used outside of the classin which it is defined.

! final! 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]) 26

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]) 27

Private Static Field

! The counter might be private:public class Point { private static int counter = 0

… }

! Now, Point.counter is no longerlegal, neither is p.counter.

! Only within Point can counter beaccessed.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 28

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; }}

Page 8: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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;

Point(int x, int y) { this.x = x; this.y = y; counter = counter + 1; }

public static int getInstanceCount() { return counter; }}

Instance Fields

Each object of class Pointinstantiated by new Point(..,..)as a copy of int x and int y.

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) { this.x = x; this.y = y; counter = counter + 1; }

public static int getInstanceCount() { return counter; }}

Class Field

Each instance of Pointshares the counter field.Class fields or staticfields are shared betweeninstances.

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; this.y = y; counter = counter + 1; }

public static int getInstanceCount() { return counter; }}

Constructor

A constructor is invokedas the first thing that happensat the new Point(…,…) call. It is used to set up fieldsin the object. new Point(…,…) does not return a referenceto the new object until the constructor has run.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 32

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; }}

Object Context

this is a special referencevalue that always referesto the object that we are currently operating inside.Here we use it to get to thefields as they are overshadowedby the parameters.

Page 9: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 33

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; }}

Accessor Method

Since counter is private in Point,we cannot access it throughPoint.counter orp.counter for any object p of class Point, so we need a wayto get to the value of counter.This is called an accessor method..

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 34

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; }

public static int getInstanceCount() { return counter; }}

Point p1 = new Point(1,2);Point p2 = new Point(3,4);…System.out.println( “# of times Point was instantiated:” + Point.getInstanceCount());

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 35

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 intgetInstanceCount() {

return counter; } public String toString() {

return “(“+x+“,”+y+“)”; }}

Point p1 = new Point(1,2);Point p2 = new Point(3,4);

System.out.println( “# of times Point was instantiated: ” + Point.getInstanceCount());

System.out.println(p1);System.out.println(p2);

Would produce:

# of times Point was instantiated: 2(1,2)(3,4)

Special method called toString; takes no argumentsand returns a String. Automatically called when an object is used in a print statement.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 36

Example

public class Point { private int x; private int y; private static int counter = 0;

Point(int x, int y) { this.x = x; this.y = y; counter = counter + 1; }

public static intgetInstanceCount() {

return counter; }

String toString() {return “(“+x+“,”+y+“)”;

}

int getX() { return x; // or this.x }

int getY() { return y; // or this.y }

void setX(int x) { this.x = x; } void setY(int y) { this.y = 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 changethem we need mutators (also called ‘setters’) as well.

Page 10: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 37

Methods

! Like fields, we can have! Instance methods (class methods)

! Again, we use the static keyword to denotethis.

! Object methods (regular methods)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 38

Non-static methods

! A regular method (non-static) can bethought of as ‘belonging to the object’

! It may reference both static and non-static 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]) 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; }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 40

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;}

Page 11: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 41

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

class

// Create a circle with radius 5Circle c1 = new Circle(5);

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 42

class

// Create a circle with radius 5Circle 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.

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 43

class

// Create a circle with radius 5Circle 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.

r = 5

objectclass Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 44

class

// Create a circle with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

Page 12: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 45

class

// Create a circle with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 46

class

// Create a circle with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

System.out.println(c1.area());double cir = c2.circumference();double pi = Circle.π;

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 47

class

r = 5

object

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

c1.area():public double area() { return π * r * r;}

Value of r from object

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 48

class

r = 100

object

class Circle { public static final π = 3.14159; public double r; public double area() { … } public double circumference() { … }}

c2.circumference():public double circumference () { return 2 * π * r; }

Page 13: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 49

classclass 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]) 50

classclass 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]) 51

classclass 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]) 52

classclass 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 with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

How do I get the radius of c1 or c2?

Page 14: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 53

classclass 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 with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

raidus in Circle is public, so it can be accessedLike this: c1.r (= 5) or c2.r (=100) but NOTCircle.r

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 54

classclass 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 with radius 5Circle c1 = new Circle(5);

r = 5

object

// Create a circle with radius 20Circle c2 = new Circle(20);

r = 100

object

raidus in Circle is public, so it can be accessedLike this: c1.r (= 5) or c2.r (=100) but NOTCircle.r

BECAUSE: r lives in an object;it is not static, and only staticfields live in classes and canbe accessed through class.field

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 55

! 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]) 56

The this keyword

! A special keyword ‘this’ can bereferenced inside objects. It refers to thecurrent context, that is, the object inwhich the code is located (NOT class,but object)

Page 15: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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 } 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]) 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 } 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 / π; }}

Problem: both the field and theparameter is called radius.

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) { // 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 / π; }}

Problem: both the field and theparameter is called radius.

Solution: The field can be referenced like any other public field by:objectRef.fieldNameBut 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

The this keyword

public class Circle { public static final double π = 3.14159; private double radius; public Circle(double radius) { this.radius = radius; } 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 / π; }}

Problem: both the field and theparameter is called radius.

Solution: The field can be referenced like any other public field by:objectRef.fieldNameBut we don’t have an object reference do we?Yes we do, it is called ‘this’

Page 16: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 61

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]) 62

Multiple Constructors

! With the Circle class we must provide aninitial radius when instantiating the class:Circle c1 = new Circle(4);

! What aboutCircle c2 = new Circle();

! That is illegal, there is no constructorwith no arguments.

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 63

Multiple Constructors

! Lets make one then, but what valueshould radius have?public Circle() { this.radius = 1; // we pick 1}

! This does the same as calling the otherconstructor with the value 1!Public Circle() { this(1);}

! This is called an explicit constructorinvocation. (Must appear on line 1)

CSC 140 Java Programming © Matt B. Pedersen ([email protected]) 64

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 allthose things have in common?! Wheels! Color! ….

Page 17: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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 intothe motorized ones and the ‘manual’ones; we could draw a diagram like this:

! All motorized vehicles are vehicles, andall manual vehicles are vehicles.

Vehicle

ManualVehicleMotorizedVehicle

Inheritance

! We could define separate classes forMotorizedVehicle and ManualVehicle:

public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}

public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}

Inheritance

! We could define separate classes forMotorizedVehicle and ManualVehicle:

public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}

public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}

Both classes have These fields, BECAUSE they areboth Vehicles.

Page 18: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

Inheritance

! We could define separate classes forMotorizedVehicle and ManualVehicle:

public class MotorizedVehicle { private int wheels; private String color; private int cc; public MotorizedVehicle( int wheels, String color, int cc) { this.wheels = wheels; this.color = color; this.cc = cc; } …}

public class ManualVehicle { private int wheels; private String color; private boolean hasSeat; public ManualVehicle(int wheels, String color, boolean hasSeat) { this.wheels = wheels; this.color = color; this.hasSeat = hasSeat; } …}

Both constructors execute partiallythe same code; The initializationOf the fields they have in commonlook alike.

Inheritance

! Perhaps we could redraw the picturefrom before:

Vehicle

MotorizedVehicle

Vehicle

ManualVehicle

Vehicle

! We can imagine aMotorizedVehicleconsisting of aVehicle plussome new stuff.

Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}

public 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; }}

Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}

public 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; }}

To inherit the fields and methodsfrom the super class we use the keyword extends.

Page 19: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

Inheritancepublic class MotorizedVehicle extends Vehicle { private int cc; public MotorizedVehicle( int wheels, String color, int cc) { super(wheels, color); this.cc = cc; } public getCc() { return cc; }}

public 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; }}

A super class’ constructor must beexecuted as well. Either explicitlyusing the keyword super, or implicitly(by not putting anything, in which case the default constructor of the super class gets called)

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.

int cc

MotorizedVehicleobject

Inheritance

! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(2,”Red”,4000);

! Object for a MotorizedVehicle is created.! Object for Vehicle is created.

int cc

MotorizedVehicleobject

int wheelsString color

Vehicle object

Page 20: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

Inheritance

! What happens when we do:MotorozedVehicle mv = new MotorizedVehicle(4,”Red”,4000);

! Object for a MotorizedVehicle is created.! Object for Vehicle is created.! Constructor for Vehicle

is executed throughsuper(4,”Red”)

! Rest of the constrctorfor MotorizedVehicleis executed.

int cc

MotorizedVehicleobject

int wheelsString color

Vehicle object

4

“Red”4000

Inheritance

! Since mv is a MotorizedVehicle thatinherits for Vehicle, all of the followingare legal:! mv.getwheels();! mv.getColor();! mv.getCc();

! But only public methods may be invokedfrom outside the object.

Inheritance

! In addition, if Vehicle has a privatemethod, then it cannot be invoked fromMotorizedVehicle.

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 otherclass. If it doesn’t inherit from any class,by default java/lang/Object is itssuper 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 thesuper class.

Page 21: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

The Abstract Modifier

! The modifier abstract can be usedon classes and methods.!An abstract method has no body:

public abstract void foo(int x) ;!An abstract class may haveabstract methods, and a classthat has abstract methods mustbe abstract

The Abstract Modifier

! Abstract classes cannot be instantiated!What would happen if you

instantiated a class with an abstractmethod?

! A subclass of an abstract classmust also be abstract unless itimplements all un-implementedabstract methods in its classhierarchy.

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 Vehicleto 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 abstractmethods.

! Maybe each vehicle sub-type has aspecific string identifying it.

Page 22: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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 motorcycle’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 subclasses 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 implementgetType()

The Abstract Modifier

• We can no longer do:new Vehicle(…);

• What about the immediate subclassMotorizedVehicle? Should it beabstract? It depends• Yes, if you don’t want instances of it• No, if you want instances of it

Page 23: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

The Abstract Modifierpublic 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() ;}

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 } // additional accessors public String getType() { return “Car”; }}

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 Modifierpublic class Arraylist<E> { private E[] elements; private int index, size;

public Arraylist() {elements =(E[]) new Object[5];index = 0;size = 5;

} public Arraylist(E[] es) {

elements = es;size = index = es.length;

}

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;}

}

public int size() {return index;

}

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;

}}

What information from this classmust we know about to use theclass?

The Abstract Modifier

! From the Account2.java file where weuse Arraylistprivate Arraylist<Transaction> transactions;transactions = new Arraylist<Transaction>();

transactions.add(t);Transaction t[] = transactions.toArray(new

Transaction[transactions.size()]);transactions = new Arraylist<Transaction>(t);

Page 24: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

The Abstract Modifierpublic class Arraylist<E> { // some internal representation of fields.

public Arraylist() { … } public Arraylist(E[] es) { … } public void add(E element) { … } public int size() { … } public E get(int index) { … } public 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 aboveare available. For all we care, any old data structure with those methods could be used.

The Interface

! We are really only interested in theinterface of the implementing class.

! As long as the class promises to makeavailable the methods we need we don’tcare about the implementation.

! We could set up a new class hierarchywhere Arraylist inherits from somecompletely abstract Collection classand 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; 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; }

. . . .}

public class Arraylist<E> extends Collection<E>{ // implement everything in Collection}public abstract class Collection<E> { public void add(E element) ; public int size() ; public E get(int index); public E[] toArray(E[] es);}

Page 25: A class Java Programmingmatt/teaching/CSC140/Chapter3-4up.pdfCSC 140 Java Programming © Matt B. Pedersen (matt@cs.unlv.edu) 5If classes are data types ….!A class is a data type,

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;

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; }

. . . .}

public class Arraylist<E> implementsCollection<E> { // implement everything in Collection}public interface Collection<E> { public void add(E element) ; public int size() ; public E get(int index); public E[] toArray(E[] es);}

Classes 100% abstract are really not classes but interfaces, and should be declared in an interfacerather than a class.

Interfaces

! Interfaces cannot be instantiated (for thesame reason abstract classes cannot)

! An interface is a contract, it tell you whatmethods 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,CIs 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?

}