Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng...

Post on 26-Dec-2015

221 views 1 download

Transcript of Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng...

Classes, Objects, Arrays, Collections and Autoboxing

Dr. Andrew Wallace PhD BEng(hons) EurIng

andrew@cs.umu.se

Overview

• Classes

• Programming in Java

• Bugs

• Arrays

• Collections

• Generics

• Autoboxing

• For loop

Classes (bits and bobs)

• Class names start with a capital letter• String• Label• Object• MyClass

• Methods start with a small letter• println• getAlignment• toString• myFunction

Classes (bits and bobs)

• Constants are written in all capitals

• Use “_” to separate words• PI (defined in java.lang.Math)• CENTER (defined in java.awt.Label)• ACTION_EVENT (defined in java.awt.Event)

• Follow the convention and your code will look like Java’s inbylt code

Classes (bits and bobs)

• Visibility• Keep things as local as possible!• Key words

• private• protected• public• default

Classes (bits and bobs)

Key word Same class Same packet

Sub class Anywhere

private yes no no no

protected yes yes yes no

public yes yes yes yes

“default” yes yes no no

Packet

Class

SubClass

Quiz

• List the four types of visibility modifiers in Java

• What is the Java convention for class and method names?

Classes (bits and bobs)

• Methods with the same name• But differ signatures!

• Signature is : method name + parameters

• public int aMethod(int x)

• public int aMethod(int x, int y)

Classes (bits and bobs)

• Overloading constructors

• Call constructor in super class• super(…);

public Square()

{

this(50, 50);

}

Public Square(int x, int y)

{

m_nX = x;

m_nY = y;

}

Classes (bits and bobs)

• String• Class

• String strText = “Hello World”;

• String methods:• String concat(String str)• char chatAt(int index)• int length()

Classes (bits and bobs)

• Simple output• Java uses class “PrintStream”

• System.out • Normal text output

• System.err• Error output

Classes (bits and bobs)

• PrintStream main methods• print• println

• Overloaded methods• For all java types

Classes (bits and bobs)

• Static• Key word• Not associated with an object

• Access without creating an object

• Avoid!• Breaks the object model• But is sometimes needed

Classes (bits and bobs)

• Static attributes• Same for all objects of a given class

• private static int nVar;

• Constants• PI• public static final double PI = 3.141592653589793;

Classes (bits and bobs)

• Static method• Class method

• No need to create an object

• Called using class name

• Math.sin(double a)

• Math.toDegrees(double angrad)

• Object.equals(Object a, Object b)

• Util.isLocal(Stub stub)

Classes (bits and bobs)

• Static methods can’t call non static methods or attributes• You have no local reference

• Main• public static main(String[] args)

• Main is where the code starts

• Creates where you need to run your program

Programming in Java

• Sequence of steps

• Control structures• if

• if … else

• switch• while• do .. while• for

Programming in Java

if

true or false

if (condition)

{

}

if(bVal)

if(!bVal)

if(nVal == 0)

Programming in Java

• if … else

• if … else if … else

if(bVal)

else

if(nVal == 0)

else if(nVal == 1)

else

Programming in Java

• Switch• Multiple if .. Else

switch(nVal)

{

case 0:

case 1:

case 2:

default :

}

Programming in Java

• while

• do … while

• When you don’t know how long you have to loop

• Condition to get out of the loop

while(!bFound)

{

bFound = true;

}

do{

…}while(!bFound)

Programming in Java

• for• When you know how many times you want to loop• for(<initialise>; <end condition>; <increment>)

for(i=0; i<strText.length(); i++)

{

}

Programming in Java

• Enhanced for loop• For arrays

for(<index> : <array>)

{

}

Index is of the type of the array!

int[] m_Array = {1, 2, 3};

for(int i : m_Array)

{

}

Quiz

• What are the three ways to create a loop in Java?

• What are the two ways to make a decision in Java?

Bugs

• Program boundary

Program

Input

Output

check

function

Bugs

• Use if statements to check data on the boundaries• File I/O• User inputs• Memory allocations

• New

• What to do?• Handel the error• Inform user• Output an error / debug message• Use the debugger to finds out what happened• throw (try … catch)

Bugs

• throws

• public void myMethod() throws <exception>

• Has to be caught or thrown again

Bugs

try

{

}

catch (<exception>)

{

}

finally

{

}

Quiz

• How do you check inputs are correct?

• What are the parts of a try statement?

Arrays

nUsefullBox

2525

Arrays

nUsefullBoxes

0 1 2 3 4

Arrays

• To create a reference to an array

type name[] arrayName;

Int[] nArrayOfNumbers;

• Instantiate

nArrayOfNumbers = new int[100];

Arrays

nArrayOfNumbers[0] = 1;

nArrayOfNumbers[1] = 2;

nArrayOfNumbers[2] = 3;

nArrayOfNumbers[i] = i + 1;

private String[] strText = {“Epsilon Eridani”, “Tau Ceti”, “Alpha Ursae Majoris”};

Arrays

• Array is a data type• type name[]• Implemented as objects

• Multiple dimensions• private double[][] Matrix = new double[5][5];

• Arrays class• Methods for manipulating arrays

• Search• Sort

Arrays

• Array copy• System

• arraycopy(src, 0, dest, 0, src.length);

• Else• Element by element in a loop

• Multi-dimensions• Call many times

• Passing arrays to methods• private void func(String[] str);

• Return from a method• public String[] aMethod(String[] strText)

Arrays

• Fail to instantiate an array • Null pointer exception

• If new fails• Out of memory exception

• Access beyond the array bounds• Index out of bounds exception

Collections

• Handling a “group” of objects in one “block”

• Lists

• Queues

• Set

Collections

• ArrayList• Class for dynamically handling arrays• Add• Remove• toArray

• A type of “collection”

Generics

• A way to use the same code with differ types• A generic algorithm

• Declare with a type parameter

• public class name<T>

public class Var<T>

{

private T t;

public void set(T t) {this.t = t}

}private Var<Integer> nVar;

Generics

public class ArrayList<E>

boolean add(E e)

E set(int index, E element)

List<E> subList(int fromIndex, int toIndex)

Autoboxing

• Primitive data types to/from classes

• Integer i = new Integer(1);

• Integer j = new Integer(2);

• Integer k = i + j;

• int x = i + 5;

• Since java 5

Autoboxing

• ArrayList myList = new ArrayList();

• myList.add(new Integer(103));

• ArrayList<Integer> myList = new ArrayList<Integer>();

• myList.add(103);

Iterator

• Class for iterating around a loop

Vector<Integer> v = new Vector<Integer>

Iterator it = v.iterator();

while(it.hasNext())

{

it.next();

}

Questions?