lecture 3. 2 introduction java is a true oo language -the underlying structure of all java programs...

33
Lecture 3

Upload: oscar-harvey

Post on 24-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Lecture 3

2

Introduction• Java is a true OO language -the underlying structure of all Java

programs is classes.• Everything must be encapsulated in a class

• that defines the “state” and “behaviour” of each object made from the class.

• A class essentially serves as a template for an object and behaves like a basic data type, e.g., “int”.

• It is therefore important to understand:• how the properties (fields) and methods are defined in a class • how they are used to build a Java program

Classes

• Contains definition for all Objects of the same type• defines the data types and names of properties• defines methods that define behavior• the “template” for all Object instances of the same type

Class Name: Circle Data Fields:

radius is _______ Methods:

getArea

Circle Object 1 Data Fields:

radius is 10

Circle Object 2 Data Fields:

radius is 25

Circle Object 3 Data Fields:

radius is 125

A class template

Three objects of the Circle class

5

Classes• The basic syntax for a class definition:

• Bare bone class – no fields, no methods

public class Circle { // my circle class}

class ClassName { [fields declaration] [methods declaration]}

6

Classes class Circle {

/** The radius of this circle */ double radius = 1.0; /** Construct a circle object */ Circle() { } /** Construct a circle object */ Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double getArea() { return radius * radius * Math.PI; }

}

Data field

Method

Constructors

7

Adding Properties (Fields):

• Add fields public class Circle {

double radius; // radius of the circledouble x, y; // center coordinate

}

8

Constructors

Circle() {}

Circle(double newRadius) { radius = newRadius;}Notice: no return value – these are not methods!

These are constructors. They make a Circle object.

Constructors are methods that are invoked to construct objects.

9

Adding Methods• A class with only data fields has no life.

• Objects created from such a class cannot respond to anything.

• Methods are declared inside the body of the class and after the declaration of data fields and the constructors.

• The general form of a method declaration is:

type MethodName (parameter-list){

Method-body;}

10

Adding Methods to Class Circlepublic class Circle { double radius; // radius of circle

double x, y; // center of the circle

//Methods to return circumference and area public double circumference() {

return (2*Math.PI*radius); } public double area() {

return (Math.PI * Math.pow(radius,2)); }}

Method Body

11

Data Abstraction

• Declare the Circle class, have created a new data type – Data Abstraction

• Can define variables (objects) of that type:

Circle aCircle;Circle bCircle;

12

Creating Circle objects cont.Circle aCircle;Circle bCircle;

• aCircle, bCircle simply refers to a Circle object, not an object itself. (e.g., this is going to be a Circle, but it isn’t yet.)

aCircle

Points to nothing (Null Reference)

bCircle

Points to nothing (Null Reference)

null null

13

Creating objects of a class

• Objects are created using the new keyword.• aCircle and bCircle refer to Circle objects

bCircle = new Circle() ;aCircle = new Circle() ;

14

Creating objects of a class

aCircle = new Circle();bCircle = new Circle() ;

bCircle = aCircle;

P

aCircle

Q

bCircle

Before Assignment

P

aCircle

Q

bCircle

Before Assignment

15

Automatic garbage collection

• The object does not have a reference and cannot be used in future.

• The object becomes a candidate for automatic garbage collection.

• Java automatically collects garbage periodically and releases the memory used to be used in the future.

Q

16

Accessing Object/Circle Data

Circle aCircle = new Circle();aCircle.x = 2.0; // initialize center and radiusaCircle.y = 2.0;aCircle.radius = 1.0;

ObjectName.VariableNameObjectName.MethodName(parameter-list)

17

Executing Methods in Object/Circle

• Using Object Methods:

Circle aCircle = new Circle();

double area; aCircle.r = 1.0;area = aCircle.area();

sent ‘message’ to aCircle

18

Using Circle Class// Circle.java: Contains both Circle class and its user class

//Add Circle class code here

class MyMain

{

public static void main(String[] args) {

Circle aCircle; // creating reference

aCircle = new Circle(); // creating object

aCircle.x = 10; // assigning value to data field

aCircle.y = 20;

aCircle.radius = 5;

double area = aCircle.area(); // invoking method

double circumf = aCircle.circumference();

System.out.println("Radius="+aCircle.r+" Area="+area);

System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);

}

}

Radius=5.0 Area=78.5Radius=5.0 Circumference =31.400000000000002

Encapsulation

• An object instance owns its state and behavior• Java provides access modifiers to define what code can access an

object's state and behavior• public

• all code can access the tagged state or behavior• private

• only instances of the enclosing class may access this tagged state or behavior• (default) package private• protected

Example of public vs private:

public class FT {private double rad;private double circ;private double area;

public FT() {rad = 1.0;setValues();

}

public FT(double r) {rad = r;setValues();

}private void setValues(){

circ = Math.PI * 2 * rad;area = Math.PI * Math.pow(rad, 2);

}

public void setrad(double r) {rad = r;setValues();

}public String printcirc(){

String s = "Radius: "+rad+" Cicumference: "+circ+" Area: "+area;return s;

}}

21

Static Variables and Methods

Static variables belong to a Class similar to global variables Use mostly for constants

easy to create bugs and undefined behavior

Static methods belong to a Class do not have access to object state (object variables, or fields) cannot call instance methods (because they use object variables) often have good uses as simple functions

formulas common to all objects in a Class are often written in a static method

Utility classes – think of the java.util… that we’ve imported – has methods we want to be able to use without having the methods attached to an object.

22

Instance Variables, and Methods

(variables and methods without "static")

Instance variables belong to a specific instance.

Instance methods are invoked by an instance of the class.

Static fields and methods

public class Creature {private int currentmood = 2;private String name = "Noname";private static int creaturecount = 0;private String[] moods = {"massively depressed","bored stiff","marginally happy", "ecstatic"};

public Creature() {creaturecount++;

}public Creature(int mood) {

currentmood = mood;creaturecount++;

}public Creature(String Creaturename) {

name = Creaturename;creaturecount++;

}public Creature(int mood, String Creaturename) {

currentmood = mood;name = Creaturename;creaturecount++;

}public String getMood() {

return (name +"'s current mood is "+moods[currentmood]);}public static String NumberinHerd(){

return ("The current number of creatures is " + creaturecount);

}}

public class mainclass {public static void main(String[] args){Creature Fluffy = new Creature (3);System.out.println(Creature.NumberinHerd());System.out.println(Fluffy.getMood());Creature Bob = new Creature(0, "Bob");System.out.println(Creature.NumberinHerd());System.out.println(Bob.getMood());Creature Killer = new Creature("Killer");System.out.println(Creature.NumberinHerd());System.out.println(Bob.getMood());}

}

Accessors and Mutators

• Accessors (e.g., getField)• public instance methods that access private data• may return different forms of the data• simple convention: getSomeProperty()

• Mutators (e.g., setField)• public instance methods that change private data• may change more than one private data element• simple convention: setSomeProperty(x)

Why are these good ideas?

public class FT {private double rad;private double circ;private double area;

public FT() {rad = 1.0;setValues();

}public FT(double r) {

rad = r;setValues();

}public void setrad(double r) { // Mutator – sets (mutates) value

rad = r;setValues();

}public double getrad() { //Accessor – gets (returns) value

return(rad);}private void setValues(){

circ = Math.PI * 2 * rad;area = Math.PI * Math.pow(rad, 2);

} public getcirc() {

return(circ);}

}

26

The null ValueIf a data field of a reference type does not reference any object, the data field holds a special literal value, null. (null reference value)

Example:

Circle circle1 = new Circle(5.0);

Circle circle2 = null;

System.out.println(circle1.getrad()); // what happens here?

System.out.println(circle2.perimeter()); // here?

circle2 = circle1; // what happens here?

System.out.println(circle2.perimeter()); // here?

circle2.setrad(4.2);

System.out.println(circle1.getrad()); //

27

2D Arrays• one-dimensional arrays to model linear collections of elements. • two-dimensional arrays represent a matrix or a table

• Example:

2-D Arrays• Make a one-dimensional array of integers:

int[] arr1d = {3,2,4,1,5};• How many elements in the array? (arr1d.length?)• How do you access the element at index 3?

• Now make an array that consists of arrays of ints:• int[][] arr2d = {{1,2,3,4},{5,6,7,8},{9,10,11,12}} ;• Or (if we don’t know the values:• int[][] arr2d = new int[3][4];

• Can you make an array of arrays of arrays? (a 3-Dimensional array?)

29

Two-dimensional Array Illustration

0 1 2 3

0 1 2

arr[1][2]= 7;

int[][] arr = new int[3][4];

0 1 2 3

0 1 2

7 2

0 1 2 3

0 1 2

66 2

1

2

3

4

5

7

8

9

10

11

12

int[][] array = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };

arr.length? arr[0].length? What data type is arr[2] ?

30

Lengths of Two-dimensional Arrays

x

x[0]

x[1]

x[2]

x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3]

x.length is 3

x[0].length is 4

x[1].length is 4

x[2].length is 4

int[][] x = new int[3][4];

(Quickly) More on Null references:

• A null reference is a pointer to nothing. • Pointers = space for address in memory

• Think of RAM, with each space in memory having its own unique address. (different spaces in memory do different things)

Circle x;• x is now a “null pointer”

• Meaning x can hold an address for a space in memory that is where a Circle will be, but currently it’s just empty

x = new Circle();• Makes a space for a circle object in memory

• memory space holds radius, circumference, area fields• Holds getRadius() method, SetValues() method,etc.

• x now holds the address of this new circle in memory.• It “points to” the circle in memory

Matrices: Making Arrays of Arrays

1. double[][] mat = new double[5][];What have I just made?

an array of 5 addresses (that will eventually point to arrays of doubles).

If I can’t do this:2. double[][] mat = new double [][]?Why can I do #1?

To create an array of arrays:You can do:

double[][] mat = {{3.2,4.1,2.5},{7.1,8.2,9.3}};Or

double[][] mat = new double[3][];mat[1] = new double[] {3.1,2.4};

Ordouble[][] mat = new double[3][];double[] arr = {7.2,3.1,2.4};mat[2] = arr;

Ordouble[][] mat;mat = new double[][] {{3.2,4.1,2.5},{7.1,8.2,9.3}};