Intro to Java and OO Programming - Department of …sengels/csc150/03f/IntroNotes.pdf1 CSC150H:...

40
1 CSC150H: Accelerated Intro to Computer Science Intro to Java and OO Programming Contents 1. Introduction History Intro to OO 2. Basic Java (no objects) Compiling Data Types Operations Methods Control Flow Statements 3. Objects Storage Creation & Allocation Visibility Inheritance 4. Advanced OO Overriding Abstract Classes & Interfaces Scope 5. Supplemental File I/O Exceptions Javadocs

Transcript of Intro to Java and OO Programming - Department of …sengels/csc150/03f/IntroNotes.pdf1 CSC150H:...

1

CSC150H: Accelerated Intro to Computer Science

Intro to Java and OO Programming

2

Contents

1. Introduction– History– Intro to OO

2. Basic Java (no objects)– Compiling– Data Types– Operations– Methods– Control Flow Statements

3. Objects– Storage– Creation & Allocation– Visibility– Inheritance

4. Advanced OO– Overriding– Abstract Classes &

Interfaces– Scope

5. Supplemental– File I/O– Exceptions– Javadocs

3

Introduction

• Why program in Java?– General history of Java

– Idea behind object-oriented programming

– Motivations

4

History of Java

Java’s origins can be traced back to C, a relatively low-level programming language

• Java is the result of evolution

• Basic syntax derived from C– Created by Dennis Ritchie, Bell Labs, 1972

– Efficient language, originally for system programming (e.g. UNIX)

– syntax:• block structure

• control statements (if, for, while, do)

• operators (arithmetic, boolean)

5

History of Java (cont’d)

Note: Simula is still used, but its main impact has been the concepts and languages that came from it.

• OO technology began with Simula and Simula 67– Created by Ole-Johan Dahl and Kristen

Nygaard, Norwegian Computing Center

– Simula introduced the idea of classes and objects, which grouped related variables & methods together

– Considered initially as a simulation language

– Gave rise to other OO languages• Smalltalk

• Eiffel

6

History of Java (cont’d)

Trivia: Java was originally called “Oak”, after the tree that was outside James Gosling’s office

• Java History– Began in 1991 with “Green Team” at Sun

Microsystems in Menlo Park, CA

– Research project: digitally-controlled devices• Technology controlled wide range of platforms,

due to its processor-independent language

– Java created in 1992 by James Gosling, Patrick Naughton & Mike Sheridan

– Digital TV applications failed to generate business; focus turned to Internet

• HTML could deliver content, but not behaviour

• Java demos caused Web pages to move and react to user

7

History of Java (cont’d)

• Java was released in 1995 – C functionality

– OO capabilities

– other nice features (e.g. garbage collection)

• Advantages: – simple, for an OO language

– secure & reliable

– platform-independent (interpreted)

– extensive libraries (esp. graphics & WWW)

• Disadvantages:– slower than C (more overhead)

– limits user ability

8

Intro to Object Orientation

• Warning: Object-oriented programming is easy to learn, but difficult to believe in

• What it is: – Related variables and methods are grouped

together into objects

– An OO program uses the interaction between these objects to perform desired tasks

• Problems:– Difficult concept for total beginners to grasp

– For experienced programmers, concept is easy but overcoming procedural habits is hard

Note: learning OO concepts is similar to learning recursion :

- it is tricky to learn

- no two explanations are the same

- people usually get it all of a sudden, usually after working on an OO program

9

Intro to OO (cont’d)

• Approach #1: Analogy– Procedural languages are like recipes:

• series of steps from initial state to final state

• recipe involves actions that are performed on ingredients in strict sequential order

– OO languages are like complex machines• machines consist of component parts, each of

which has its own function

• when combined, components combine with each other to perform a larger function

• user interacts with interface to highest level

– More conceptual, less coding

Analogy examples:

- cars

- VCRs

- computers

- pianos

- etc.

10

Intro to OO (cont’d)

• Approach #2: Design-based– OO programming involves breaking down

large task into smaller component tasks

– Each component task has its own object• data storage

• methods

• external interface

– UML (Unified Modeling Language)• diagram-based design; draws objects as boxes

containing data & methods, with connecting lines indicating relations between objects

• Excellent for planning; introduces the concept of unit testing.

• Can be hard for procedural programmers

UML:

- More information can be found at:

http://www.omg.org/uml/

11

Intro to OO (cont’d)

• Approach #3: Examples– Implement a board game with OO

programming (e.g. Scrabble)

– Scrabble object would have components:• Board object

• TileBag object

• 4 TileRack objects

• 100 Tile objects

– Bag object would contain several Tile objects initially, but would have methods to remove Tiles to add to Board and TileRack objects

– “Practice makes perfect” philosophy.

Bingo!!

- Java’s website has an example, in the form of a Bingo game:

http://java.sun.com/docs/books/tutorial/together/bingo/

12

Intro to OO (cont’d)

• Object-oriented terminology– object = a data structure that combines variables and methods

that operate on these variables. It is assumed that the object embodies a general concept.

– class = the general data type that describes the construction of a particular object. If an object is like a house, the class is the blueprint for that type of house.

• in Java, one describes the class first, and then creates objects, which are instances of that class.

– message = the communication between objects, usually in the form of parameters passed into method calls

– dereferencing = the act of accessing the internal variables or methods of an object or class

• in Java, this is done with the ‘.’ character (e.g. System.out)

13

Intro to OO (cont’d)

• More object-oriented terminology– inheritance = the adoption of one class’s structure and

behaviour into another. If class B inherits from class A, class B takes on the variables and methods of class A, and is able to add more of its own

• e.g. Given a Car class, one could create a Porsche class that inherits from Car, so Porsche has all of Car’s characteristics

• Porsche can do all the things that Car can do, but could also have added variables and methods

– superclass = in an inheritance relationship, the class that is being inherited from (Car)

– subclass = in an inheritance relationship, the class that is inheriting from the other (Porsche)

14

What’s the Point of OO?

• Modularity:– Keep all the variables and methods pertaining

to a concept together. Easier to understand, easier to maintain.

• Information hiding:– Certain object components are better hidden

• variables that record an object’s internal state

• methods that are only useful for processing the data within an object.

– Such variables & methods are kept private, meaning that they are not visible from outside the object. This prevents unwanted changes to the object’s internal state, and simplifies how the object can be used.

Vroom vroom:

A good analogy to refer to here is the car example.

- Understanding how the car works is easier when it’s made of individual parts.

- To drive a car, you don’t care how the engine or any other internal part works.

15

When is OO Used?

• The project has multiple components whose individual behaviour can be modeled

• Changes are anticipated in the future

• The system is large and complex

• There is a hierarchy of types, or a reuse of behaviour

16

Common Questions

• What’s the difference between objects and struct in C?– Answer: Information hiding. The struct data structure in C is a

grouping of variables, which is little better than having all the variables listed globally. Objects restrict access to internal variables and methods that shouldn’t be tampered with.

• What use does inheritance serve?– Answer: Reuse of code, maintaining consistent behaviour. If a

Car has certain functions, there’s no reason why those functionsshould be any different in a Porsche.

• Are object-oriented approaches necessarily better?– Answer: Not always. The idea is intuitive for some applications

(e.g. large project with multiple components), but for simple, linear programs you’re better off not using objects.

17

Basic Java

• Basic syntax and structure, no OO yet.– Compiling

– Data Types

– Operations

– Methods

– Control Flow Statements

18

Basic Java Syntax

• Compiling & running a program

• Linear components:– Data types

– Methods

– Program structure

• OO components– Classes & objects

– Inheritance & polymorphism

19

Compiling and Running

• Java programs are stored in text files that end in *.java

• Software Development Kit (SDK) must be installed to compile and run the programs

• No program editor is supplied with the SDK

public class HelloWorld

{

public static void main(String args[])

{

System.out.println(“Hello World!”);

}

}

HelloWorld.java

20

Compiling and Running

• Compiling (javac):– javac runs Java compiler.

If successful, then code is correct and *.class file is created. Otherwise, error messages are displayed.

• Running (java):– java runs byte-code

interpreter which executes program.

– Note: *.class suffix is not needed for this command

C:\Code\Hello> javac HelloWorld.java

C:\Code\Hello> java HelloWorld

Hello World!

C:\Code\Hello>

21

Class Structure

public class GeneralClass

{

<variable declarations>

<method declarations>

}

• Class structure resembles example below:– Each class declaration is contained within its own file.

– Finer distinction: Each file can only have one public class declaration

• The method section of each class may or may not contain a main method:– Note: At least one class in the project must have a main

method for the project to be executable.

22

Comments

/* This is one kind of comment, that can span several lines. Don’t forget to put the closing characters at the end.

*/

// This is the other type of comment.

// It covers the entire line

// and requires a new set

// of slashes for each new line.

23

Data Types (primitives)

Primitive types:

When any variable is declared, a small amount of space is allocated for that variable.

- “Primitive” data types refer to types where the variable’s value can be stored directly in the allocated space.

- More complex data types (objects) store a memory address in the allocated space instead. This address acts as a reference to where the object can be found.

• Data type rules– Must be declared with name & type

– Value is optional (default is “zero”)

– Can’t have two variables with same name and different type

– Naming convention: Consecutive words, first letter of each word capitalized, except for first word.

• e.g. numBuffaloWashed

– Primitive types:• integers

• characters

• booleans

• floating point numbers

24

Data Types: Integers

• 3 types of integers– byte: 8 bits– short: 16 bits– int: 32 bits– long: 64 bits

• Operators:– add: + – subtract: -– divide: / – multiply: *– modulus: % – assignment: =– equality: == – inequality: !=– less than: < – less than or equal: <=– greater than: > – greater or equal: >=– increment: ++ – decrement: --– (bit shift left): << – (bit shift right): >>, >>>

Short or long?

This can usually be ignored for this class, but it’s good to know for projects that use very large integers

Two other modifiers are signed and unsigned. Unsigned integers double the integer range by neglecting negative values.

25

Data Types: Integers

• Rounding truncates numbers towards zero– Example:

• 2.3

• 2.6

• -2.6

• Remainder operation (%) returns smallest signed remainder value.– Example:

• 10 % 3 =

• 10 % -3 =

• -10 % 3 =

• -10 % -3 =

26

Data Types: Characters

• Characters are 16-bits long

• Declared as char

• Literals are assigned between ‘ ‘ marks

• Note: Special character ‘\n’indicates new line

char c1 = ‘a’;

char c2 = c1;

c1 = ‘b’;

27

Data Types: Booleans

• Declared as boolean

• Occupies 1 bit in memory

• Values are true and false (case-sensitive)– Not equivalent to integers (unlike C & C++)

• Operators:– NOT: !

– AND: &, &&

– OR: |, ||

– XOR: ^

28

Data Types: Floating Point

• Declared as float or double– float: 32 bits

– double: 64 bits

• Both use IEEE 754 floating point standard

• Same operations available as with integers (except bitwise shifts)

Number Literals:

2 int

2L long

2.0 double

2.0D double

2.0F float

0.2e1 double

29

Data Types: Strings

• Not a primitive, but we’ll overlook this for now

• Declared as String (case-sensitive)

• Literals are assigned between “ “ marks

String s1 = “Hello world!”;

String s2 = new String(“Hello world again!”);

System.out.println(“Hey!”);

System.out.println(s1);

System.out.println(s1);

String trivia:A string is actually an array of characters, with methods that modify it (append, concatenation, substring, etc.)

30

Constants

• Denoted by keyword final in front of type declaration

final double d1 = 2.0;

• Prevents value from being modified– e.g. PI, MAX_SIZE

• Naming convention:– write constants in all caps, with words separated

by underscores

31

Data Assignments

• Copies the value on the right to the variable on the left– important later, with reference types

• i += 2 is equivalent to i = i + 2;• Increment (++) and decrement (--)

operators can be placed before or after a variable to increase or decrease its value by 1– before the variable (prefix): value is

changed before variable is used in other operations

– after the variable (postfix): value is changed after variable is used in other operations

Assignment Operators:

+= -=

*= /=

%= &=

|= ^=

>>= <<=

>>>=

32

Casting

• “Casting” a variable = telling the program that the variable is of a different type than how it was originally cast– Example: casting a double as an int for

integer calculations

– No arbitrary casts.

• Also used often with references and objects (discussed later).

Assignment Operators:

+= -=

*= /=

%= &=

|= ^=

>>= <<=

>>>=

33

Reserved Wordsabstract double int strictfp **

boolean else interface super

break extends long switch

byte final native synchronized

case finally new this

catch float package throw

char for private throws

class goto * protected transient

const * if public try

continue implements return void

default import short volatile

do instanceof static while

* not supported ** recently added

34

Methods

• Declared as:

<return type> <method name> (<parameters){

<statements>}

• Naming convention: same as variables. Names should be short, but meaningful (e.g. printOutput)

• No trailing semicolon needed after }• Parameters can be left blank, return

type can be void.

Methods:

For teaching methods to new programmers, I like bringing in a recipe in cooking terms and in Java terms, to help them think about how to put instructions together.

Other suggestions?

35

Methods (cont’d)

• Example:

public class HelloThere

{

String name = “Steve”;

public static void main(String[] argv)

{

System.out.println(“Hello ” + name + “!”);

}

}

– When java HelloThere is run at command line, interpreter looks for main() method in HelloThere, and executes it.

– Several classes in a project can have main() methods, but only the one entered at the command line is run.

36

Method Overloading

• Multiple methods within a class are allowed to have the same name– must have different input parameters

to differentiate methods– implies that methods have same or

similar operations– useful for class constructors (discussed later)

• Examples:– “-” operator– add(String targetStr, char sourceChar)

add(String targetStr, char sourceChar, int position)

• Operators– some are overloaded already (e.g. “+”)– Operators cannot be overloaded by program designer

37

Control Flow Statements

• if statements test only on boolean conditions

• <statement> can be replaced with a statement block, which is a set of statements enclosed with {…}

• No statements are permitted between the end of the if statement block and the else keyword.

if (<true/false condition)

<statement>

else if (<true/false condition)

<statement>

else

<statement>

-----------------

if (length < 0)

{

System.out.println(“out of bounds”);

return;

}

else

System.out.println(“A-okay!”);

38

Control Flow Statements (cont’d)

• Similar to if statements:– <cond> ? <val1> : <val2>

– switch (<cond>) { case…}

• ? operator tests boolean value of <cond>. Statement returns <val1> if condition is true, <val2> if condition is false.

• switch statement tests a value, and runs the code after the case line that corresponds to that value

– break is used to exit the statement block

int month = ___;int numDays;...numDays = (month == 2) ? 28 : 30;switch (month){

case 1:numDays++;break;

case 3:numDays++;break;

case 5:case 7:case 8:case 10:case 12:

numDays++;default:

// don’t do anything.

}

39

Control Flow Statements (cont’d)

• for loop syntax:for (<initial>; <test>; <update>) { … }

• while loop syntax:while (<test>) { … }

• do loop syntax:do { … } while (<test>)

– <initial> = intial statement to perform• usually initialization, like: int i = 0

– <test> = condition to test for. If condition is true, continue looping.

• Example: i < 10– <update> = statement to perform with each

iteration• usually increment, like: i++

for Loop Comparison

Pascal:for i=1 to 10 do

Fortran:do i=1, 10

Java:for(i=1; i<10, i++)

Why so complicated in Java? Power. Java allows user to change the step size & stopping condition to suit various problems.

40

Control Flow Statements (cont’d)• Altering control flow

– break: break out of current block (denoted by {…}) and execute code statements after block

– continue: stop current block iteration, return to beginning of block and continue running from there

– return: stop running method entirely, and return control to calling program

public boolean test_prime(int inputValue){

int i = inputValue - 1;boolean returnValue = true;if (i < 0) i = -i; // take care of negative caseif (inputValue == 0) return true;while (i != 1) {

if (inputValue % i == 0){

returnValue = false;break;

}i--;

}return returnValue;

}

41

Review

• Data types– int, boolean, char, double– constants, operators, casting, assignments

– reserved words

• Methods– declaration, structure

– control flow statements

• Next: Objects

42

Objects

• The ins and outs of object-oriented programs– Storage

– Creation & Allocation

– Visibility

– Inheritance

43

Objects & Classes

• As stated earlier, a class describes an encapsulation of variables and methods into a single data structure

• Objects are instances of the data structure described by a class

• Classes and objects represent a concept, or a function. – One class for each component of a

project GOOD

– One huge class for your entire project

BAD BAD BAD

Objects vs Classes

One of the most common confusions in Java is the difference between objects and classes. Select whatever answer suits you the best:

- classes are descriptions of a data structure, objects are the instances of them

- classes are like blueprints of buildings, objects are like the buildings themselves

- a class is a data type, like int. Objects are like the variables of that data type.

44

Example: String

• String is an object, although it’s often treated like another variable– State: array of characters

– Behaviour: operations on those characters

• Captures concept of a string– sequence of characters that

can be accessed and manipulated

public class String{

private char[] chars;

public int compareTo(String str){

// code for comparing Strings}

public char charAt(int index){

// code for getting character// at index position

}

}

45

Important Properties

• Classes promote abstraction– Modularity: All variables and methods

relating to this concept are encapsulated in this class.

• Allows changes to the class to happen independent of the rest of the software

• Allows the class to be used in multiple contexts

– Information Hiding: Prevent user from seeing class’s internal implementation

• Protects user from having to know implementation when using class

• Protects programmer from having internal data or methods abused by user

Real World Objects

Software objects were inspired by objects in real life. Describing the “state” and “behaviour” of the following everyday objects:

Examples:- vehicles

- electronics (VCR, PS2)

- tools

- food

- any others?

46

Storage Issues

• The space for a primitive type (16-64 bits) is too small to store the components of an object

• Solution: allocate a block of space in memory to store the object, and record the address of this block in the space for a primitive type

reference type

0x1000

String“Hello World!”char[] chars

int compareTo(String str)

char charAt(int index)

String s1 = “Hello World!”;int index = 42;

42

0x1000

s1 index

47

Storage Issues (cont’d)

• This adds an extra subtlety to creating object variables– declaration: name and type of object

– allocation: creation of space for object

• Syntax:<object type> <name> = new <object type>

– new allocates space for the object, and returns the address of this allocated space to be assigned to <name>.

– Without RHS, <name> gets null value.

– Special cases: Strings, arrays

• Note: reference is not a pointer– No pointer arithmetic

– Cannot extract pointer directly

– If reference is lost, space is garbage collected

Real Life, Revisited

One of the most common coding errors is the null pointer. This is almost always because an object variable is declared, but no object is assigned to it.

Here are analogies that can clear up the confusion:

- buying an empty lot, but forgetting to build a house

- buying a leash, but not attaching it to the dog

- deciding on the name for a child, but forgetting to have the baby

48

Storage Issues (cont’d)• Example:

• What gets printed out?

public void stringTest(){

String s1 = “Hello”;String s2 = new String(“World”);String es1 = new String();String es2 = “”;String ns1;String ns2 = “null”;

System.out.println(s1 + s2);System.out.println(es1);System.out.println(es2);System.out.println(ns1);System.out.println(ns2);

}

49

Creating Objects

• When an object is created, a method within the class called a constructor is automatically called– The constructor is a method with the same name

as the class, but has no return type

– May have parameters, which must be specified when the object is created

– Used to initialize the object’s data values

– If no constructor is specified, then default constructor makes the object and initializes all data values to “zero”

• Example: new String(String str) Initializes string to str

new String() Initializes string to “”

What goes up…

Many OO languages feature destructors, which are executed whenever an object is closed. Usually this is to free up any memory the object may have allocated. Java has no such construct, and uses the garbage collector to free up unused memory

50

Accessing Objects

• The . operator is used to “dereference” the object (i.e. to access its contents)

• Syntax:

<objName>.<variableName>;

<objName>.<methodName>(<parameters>);

– Example:

String s1 = “Hello World!”;

int stringLength = s1.size();

Nested Dereferencing:

Q: Object A contains an instance of object B called bPart. Object B contains an instance of object C called cPart. Given an object a1of type A, how do you get access to the C component of a1?

A:C result = a1.bPart.cPart;

What does this assume about bPart and cPart?

51

Comparing & Equating Objects

• Since object variables just store an address, the “=“ and “==“ operators have different behaviours– “a = b”: assigns the address of b’s object to the address of a’s

object make both point to same object– “a == b”: checks if the address of a’s object is the same as the

address of b’s object if a & b refer to the same object

• To check if the value of two objects is the same, use the equals(…) method, implemented in most classes– Example:

String s1 = “Hello World!”;String s2 = “Hello World!”;if (s1 == s2) {...} // falseelse if (s1.equals(s2)) {...} // trueelse if (s2.equals(s1)) {...} // also trues1 = s2;if (s1 == s2) {...} // now true

52

Arrays

• Arrays are structures that hold several data values, of either primitive or object type

• Declaration syntax:– int[] intArray;

creates reference to array, null value

– int[] intArray = new int[10];creates array of 10 integers, zero values

– int intArray[] = { 3, 1, 4, 1, 5 };• creates and initializes 5-element array

– String stringArray[] = new String[5];• creates array of 5 Strings, null values

3

1

4

1

5

intArray

stringArray

53

Arrays (cont’d)

• Arrays are treated like a primitive data structure in many languages, but in Java they are objects with special notation and operators– direct addressing: intArray[2]

– array length: intArray.length

– no array constructor

– compiler checks out-of-bounds condition

• Note: array indexing goes from 0 to length-1

• Possible to have multidimensional arrayint[][] intMatrix = new int[10][10];

Array Reminder

Arrays are just boxes with room for objects. Just because you create a box to hold certain objects, doesn’t mean that it comes with those objects inside it already. An array’s contents have to be allocated separately, or else you can’t refer to them.

54

Visibility Modifiers

• How does Java implement information hiding?– keywords that change the visibility of a class’

variable or method

– used for declarations, not within a method

• Four keywords:– private = a class’s private variables and methods

can only be seen by instances of that class

– public = a class’s public variables and methods can be seen by instances of any class

– protected = descendants of a class inherit that class’s protected variables and methods

• inheritance will be discussed shortly

– package = allows other classes within the same package to see the class’s non-private variables

• the default, if no other modifier is used

Analogies, again

Visibility modifiers are like secrets. Some secrets you can tell anybody (public). Some you keep to yourself (private). Some you can only pass on to family (protected), and some secrets can only be shared with friends (package).

55

Visibility Modifiers (cont’d)

• Most class variables are kept private. Class’s methods are used to access or modify internal data– accessor methods = methods that directly set or retrieve the

value of internal state variables– Example:

public class Complex {

private double real;private double imag;public Complex() { real = 0.0; imag = 0.0; }public void setReal(double value){

real = value;}public double getReal(){

return real;}

}

56

Visibility Modifiers (cont’d)

• static keyword– static variables and methods in a class are shared among all instances

of that class– Why is this useful?

• Common variables (PI, totalCount)• Shared code (usually with static variables)

– Side benefit:• ability to invoke methods without creating an instance first (e.g. main).

v1 v2

m1 m2

v1 v2

m1 m2

v1 v2

m1 m2v1 v2

m1 m2

without static: with static:

v1

m1

v1

m1

v2

m2

v1

m1v1

m1

static space

57

Inheritance

• Motivations– code reuse

– draw relations between similar classes

• Encapsulation and inheritance are the most fundamental principles of object-oriented programming

• Idea: define new classes as extensions of old ones

Real-life Inheritance

-In manufacturing, new products rely on inheritance ideas, like computers improving on legacy systems, or cars having basic and “special edition” models.

-Be careful about your choice:

- OO inheritance is more like the car analogy, with general and specific models.

- The computer analogy is more like the genetic concept of inheritance, when new generations are only created to replace old ones.

58

Inheritance (cont’d)

• Inheritance terms:– B & C are derived from A; D & E are derived from B

– B is the superclass of D and E

– B is the subclass of A

– A and B are ancestors of D

– B, D and E are descendants of A

– A is the root of the hierarchy (the Object class, in Java)

A

B

D

C

E

inheritance diagram:(hierarchy)

59

Inheritance Rules

1. Subclasses inherit only the variables and methods that are public or protected in their superclass

2. Classes may only inherit from one other class at a time.

3. No loops in inheritance diagram

4. All classes inherit from the Object class (Java root)

5. An object can be assigned to a variable of an ancestor’s type, but not a descendant’s.– Example:

Object o = new String();String s = new Object();

Good (String is an Object)Not Good

60

Example: Containerpublic class Container extends Object{

protected Object data[];protected int size;public int getSize(){

return size;}

}

public class BasicList extends Container{

protected void insertAt(Object obj, int index){

if (index < 0 || index > size || isFull()) return;

for (int i = data.length-1; i > index; i++)data[i] = data[i-1];

data[index] = obj;size++;

}public boolean isEmpty(){

return size == 0;}public boolean isFull(){

return size == data.length;}

}

Object

Container

protected Object data[]protected int sizepublic int getSize()

BasicList

protected void insertAt(…) protected void removeFrom(…) public boolean isEmpty() public boolean isFull()

61

public class List extends BasicList{

public void insert(Object obj, int index){

insertAt(obj, index);}public Object remove(Object obj, int index){

return removeFrom(index);}

}

public class Stack extends BasicList{

public void push(Object obj, int index){

insertAt(obj, size);}public Object pop(Object obj, int index){

return removeFrom(size-1);}

}

public class Queue extends BasicList{

public void enqueue(Object obj, int index){

___________________;}public Object dequeue(Object obj, int index){

_________________________;}

}

Object

Container

protected Object data[]protected int sizepublic int getSize()

BasicList

protected void insert(…) public boolean isEmpty() public boolean isFull()

List

public void insert(…) public Object remove()

Stack

public void push(…) public Object pop()

62

Wrapper Classes

• For classes like List, Queue or Stack, Object types are used

• To store primitives, the values would need to be converted to Objects

• Wrapper classes store the primitive value internally, with appropriate methods for each primitive type (e.g. conversion to Integer, comparison between Character values)

Wrapper Classes:

Boolean

Byte

Character

Double

Float

Integer

Long

Short

63

Advanced OO

• Time to strain the brain– Overriding– Abstract Classes & Interfaces– Scope

64

Overriding

• What if a method is redefined in a subclass?– Without inheritance, this isn’t

a problem. Classes would be separate, so no interference

– If methods are private, then not a problem. They would be invisible outside the class, so no interference

– With inheritance & public methods: do you use the inherited method, the local method, or some other method? Hmm….

Shape

public void draw()

Line

private int startX, startY,endX, endY

public void draw(…)

Circle

public int centreX, centreYpublic void draw(…)

Arrow

public int headSizepublic void draw(…)

Arc

public int centreX, centreYpublic void draw(…)

65

Overriding (cont’d)

• Overriding = Providing a different implementation of a method in a subclass of the class that originally defined the method– Note: overriding only applies to methods, not variables

• General rule: Use the method that is appropriate for the underlying object. – if the method is defined in the current class, use that

implementation

– if the method is not defined in the current class, then look up the hierarchy and use the lowest non-private implementation

– Note: These rules apply to the class of the underlying object. This means that if the variable has been assigned to an object of a subclass type, use that subclass with the rules above.

Object obj1 = new Object();Object obj2 = new String(“Hello”);

66

Overriding Object• Certain methods are defined in Object, and meant

to be overridden by all classes. Important ones are:– equals(Object obj) = checks if the current object and the

input object are “equal” to each other. Different from ==, which checks if they are the same object.

– clone() = creates and returns a copy of the object– toString() = returns a String representation of the object

public class Container extends Object{

Object[] data;...public toString(){

if (data.length == 0) return “{}”;String returnString = new String(“{“);for (int i=0; i<data.length; i++)

returnString += data[i] + “,”;return returnString + “}”;

}}

67

Abstract Classes

• From the previous example, the Shape class isn’t specific enough to be useful as an instance (e.g. draw() )

• Solution: – Allow Shape to exist, since it outlines

useful common functionality – Declare the undefined method and the class in general to be

abstract, thus preventing any instances of the class to be made

• keyword: abstract

68

Abstract Classes (cont’d)

• Rules:1. An abstract class is a class where one or more of its

methods is abstract • not all need to be

• variables cannot be abstract

2. Declaring variables of an abstract class is allowed. Making instances of an abstract class is not.

3. For a descendant of an abstract class to be instantiated as an object, all of the abstract methods it inherits from its superclass must be overridden

69

Abstract Class Example

public class Shape{

public abstract void draw();// draw Shape, undefined here => abstract

}

.

.

.// in a method somewhere...Shape[] shapeArray = new Shape[10];shapeArray[0] = new Line(0,0,10,10);shapeArray[1] = new Circle(3,3,2);shapeArray[2] = new Arc(5,5,10,10,7,7);shapeArray[1].draw();...

70

Interfaces

• Abstract classes guarantee that any Shape may have the draw() method called from it.

• This restricts this required behaviour to members of the same family of classes, since this behaviour is considered useful for this family of objects

• What about comparing two objects of the same class? (e.g. String a is greater than String b)– operation isn’t family-dependent, since many classes will

need it– only way to implement it with abstract classes is at the Object level, which fails since not all Objects are meant to be compared

• Solution: interfaces

71

Interfaces (cont’d)

• Interfaces are collections of abstract methods (without the abstract keywords)

• collection of methods describe some high-level behaviour (e.g. Comparable)– general– useful

• If a class implements an interface, that implies that it must implement all its methods

• (Interfaces may also declare constants)

Two Interface Ideas

- User Interface = software designed to allow users to deliver commands to application

- Class Interface = specification of the required functionality of a class.

72

• Declaring interfaces:

• Implementing interfaces:

Interface Syntax

public interface <interface name>{

// method signatures here}

public class <class name> implements <interface name>{

// declare class variables and methods// methods must override interface methods

}

73

Abstract Classes vs. Interfaces

• Similarities– both describe behaviour that a class must implement before

it may be instantiated as an object– abstract methods and interface methods are method

signatures with no implementation block

• Differences– Main conceptual difference: Abstract classes are classes,

interfaces are not. Abstract classes describe concepts that are specific to a family of classes. Interfaces are not part of the class hierarchy, and so can describe the behaviour of completely unrelated classes

– A class can only inherit from one abstract class; a class can implement multiple interfaces

– Abstract classes can be partly implemented; interfaces are completely abstract (no abstract keyword needed)

74

Interface Examples

• Comparable:– Sorting algorithms want to be able to compare

elements pairwise to determine the order of the elements

– Assumes that objects to sort are of the same type

• ActionListener– For GUIs, each component (button, checkbox,

etc.) needs to be able to listen for “events” (clicking, double-clicking) to know when to act.

– The ActionListener interface specifies a behaviour for each event, so each component can be assigned an ActionListener if it needs to handle events

• General:– Parameters to methods can be specified using

interfaces, meaning that these methods would require a particular functionality instead of a particular class

Conveying Interfaces

Hopefully by this point, the concept of interfaces is clear and makes sense. If not, here are other ways of discussing them:

- abstract classes and interfaces like family duty vs. club membership.

- interfaces as contract, implying duties and privileges that come with it

-Food vs. Edible. Food is abstract class, describes class family. Edible is class characteristic, can be assigned to many unrelated classes (like Flowers)

75

Scope

• With all the inherited components, multiple variables with the same name will co-exist. If a variable occurs in a method, how do you know what it refers to?

• Order in which to look:1. In local block (if, while, for)

2. In local variable declarations (method space)1. check both local and static variables

3. In local parameter list (static & instance)

4. Class variable list (static & instance)

76

• this: refers to current object’s methods and variables

• super: refers to variables and methods of object’s superclass– circumvents usual scope rule– cannot be chained (e.g. super.super.doThis())

• instanceof: boolean operation, checks if object of general class A is really of subclass B

More Inheritance Keywords

public int local = 0;...public void local_method(int local){

this.local = local;}

Object unknownVar = someArray[0]if (unknownVar instanceof String)

doStringOperation();

77

Supplemental

• Useful things to know– File I/O

– JavaDocs

78

File I/O

• Reading & writing files can be done in multiple ways:

– streams– readers

• Good to know all of these techniques; enough to know one that works for you (see right)– FileReader class

reads file– BufferedReader

uses FileReaderto obtain text

– Writing is same, with Writerexchanged for Reader

// load the selected file, return a String representationpublic String LoadFile(String filename) {

String returnString = new String();String line;try {

FileReader file = new FileReader(filename); BufferedReader buf = new BufferedReader(file); while((line = buf.readLine()) != null) {

returnString += line + '\n'; lines++;

} buf.close(); } catch(IOException e) {} return returnString;

}

79

Exceptions

• Java has a separate class (Exception) for problems that occur at runtime (i.e. not compiling errors)– Errors: Something terminally bad has occurred (hard drive is

gone, network connection is lost)– Exceptions: The program has violated the specifications of

one of its components (indexing out-of-bound array index, trying to access null pointer)

• Runtime exceptions are a particular subclass of Exception that will end a method, but not end a program. All other exceptions will terminate the program, stating the class it was in as it ends the method in that class.

• We will cover exceptions in more detail later.

80

JavaDocs

/** This is the typical format for Javadocs. This comment at * the top will appear in the main text of the documentation, * under the listing of the parameters described below.* If you want to create a link to another class, do it like* this: {@link String}. * <p> * This method is pretty trivial, but when formatted using the * Javadoc tool (included in the SDK), it makes reviewing another* person’s code much easier. Take a look on the next page to see* the output.* * @param firstName A string representing the first name of the user* lastName A string representing the last name of the user* @return The message to the user* @see String*/

public String sayHello(String firstName, String lastName) {

String returnString = new String(“Hello ”);if (firstName != null && lastName != null)

return returnString + firstName + “ “ + lastName;return “Hi”;

}