unit 6: object-oriented programming: objects and classes jin sa

40
Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Post on 22-Dec-2015

232 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Unit 6: Object-oriented Programming: Objects and Classes

Jin Sa

Page 2: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Objectives of this unit

• To learn how to declare a class and how to create an object of a class.

• To learn how to send messages to other objects.• To understand the difference between instance

and static variables and methods.• To manipulate objects in arrays.• To understand the use of various visibility

modifiers.• To know how to use the exception mechanism.

Page 3: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Defining and using classes and objects

• An object has a unique identity, state, and behaviours.

• The state of an object consists of a set of data fields with their current values. These data fields are called attributes.

• The behaviour of an object is defined by a set of methods.

• Classes are constructs that define objects of the same type.

Page 4: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Defining classes – see SimpleCircle from unit6 section B

public class Circle { double radius = 1.0; Circle() { } Circle(double newRadius) { radius = newRadius; } /** Return the area of this circle */ double findArea() { return radius * radius * 3.14159; }}

• Radius is the data field of the Circle class. The data fields are often referred to as attributes.

• The class also defines three methods: Circle(), Circle(double newRadius) and findArea(). These three methods will determine the behaviour of any circle created from this template.

Page 5: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Methods

• The format of a method is type_of_value_returned name_of _method(list of parameters)

• type_of_value_returned can be void if the method does not return any valuevoid setRadius(double newR){

radius=newR;}

• List of parameters can be empty if the method does not take any parameter.– findArea().

Page 6: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Constructors

• Circle() and Circle(doubleRadius) are called the constructors.

• A constructor of a class is invoked when an object of that class is created. It plays the role of initializing objects.

• A class may have more than one constructor, more than one way to create an instance.

• Constructors must have the same name as the class itself.

• A constructor with no parameters is referred to as a no-arg constructor, e.g. Circle().

Page 7: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Creating objects – new(see TestSimpleCircle)

• To create an object, we use the new operator. – new Circle(); – new Circle(2.5);

Page 8: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Object references and accessing objects via object references

• To reference an object, we can assign an object to an object reference variable. For example:– Circle myCircle = new Circle();

• myCircle is an object reference. It is now pointing to an instance of Circle.

• An object’s data and method can be accessed via the object reference, e.g.– myCircle.radius – myCircle.findArea()

Page 9: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

More about object references

c=new Circle();

Page 10: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

More about object references (2)

Page 11: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student Activity

• Complete Unit 6 student activity 6.1

Page 12: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Visibility modifiers

• public: The data or method is visible to any class in any package.

• private: The data or methods can be accessed only by the declaring class.

• By default: the data or method can be accessed by any class in the same package.

Page 13: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Visibility modifiers (2)

Page 14: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

get and set methods • Following the principle that data should be encapsulated, we should

declare data field private.• However, private attributes are not accessible from outside its object. • To allow clients, i.e. other objects, to access or modify a private data field

in a controlled way, we can provide public get method and set method to manipulate the private data field, e.g.

 

public double getRadius(){

return radius;

}

public void setRadius(double newR) {

if (newR<1) radius=1;

else radius=newR;

}

Page 15: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity (may skip)

• Complete unit 6 student activity 6.2

Page 16: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Passing object references as parameters

• An example of passing an object as a parameter to a method:

public boolean equalSize(Circle o) { return radius==o.getRadius();}

• A main method that illustrates the use of the

equalSize method.

public static void main(String[] args) { Circle c1= new Circle(2.0); Circle c2 = new Circle(1.5); System.out.println("C1 and C2 are of the same size: " + c1.equalSize(c2));}

Page 17: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Returning object reference from a method

• A method returns a new object public Circle biggerCircle() { double newR=radius*2; //new circle radius is twice as big as //the current circle’s radius return (new Circle(newR)); //return a new circle object with the bigger radius. }

• Calling the methodpublic static void main(String[] args) { Circle c1= new Circle(2.0); Circle c2 = c1.biggerCircle(); double r = c2.getRadius();}

Page 18: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity

• Complete unit 6 student activity 6.3

Page 19: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Manipulating array of objects• To declare an array of objects. – Circle[] circleArray = new Circle[10];

• To create 10 circle objects:for (int i=0; i<10;i++) {

circleArray[i]=new Circle(10+i);

}

Page 20: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Example of array of objects… …Circle[] circleArray=new Circle[10]; //assume that circleArray has been initialised //with 10 circle objects. public void printCircleArray() { for (int i = 0; i < 10; i++) { System.out.println("Radius: "+ circlearray[i].getRadius()); System.out.println("Area:+circlearray[i].findArea()); }}… …

Page 21: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity

• Complete unit 6 student activity 6.4.

Page 22: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

ArrayList• Limitations with array is that its size is fixed once the array is

created. • Java provides the ArrayList class in which the size of the array

is not fixed. Some of the commonly used methods in the ArrayList class:– void add(Object o) appends o at the end of the list– void add(int index, Object o) adds o at the specified index in the list– boolean contains(Object o) returns true if o is in the list.– Object get(int i) returns the element at position i in the list.– boolean isEmpty() returns true if the list is empty– boolean remove(Object o) removes element from the list.– boolead remove(int i) removes the element at position i.– int size() returns the number of elements in the list

Page 23: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

An example of ArrayListpublic class ArrayListCircles {

ArrayList<Circle> circlelist=new ArrayList<Circle>();

public ArrayListCircles() { for (int i=0;i<10;i++){ circlelist.add(i, new Circle(i)); } } public void printCircleList() { System.out.println("Radius\t\t\t\t" + "Area"); for (Circle c: circlelist){ System.out.println("Radius: "+ c.getRadius()); System.out.println("Area: "+c.findArea()+"\n"); } }… … }

Page 24: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity

• Implement the ArrayList example. Compare it with the implementation in Student activity 6.4

• Try to add more than 10 circles and/or remove circles from the array for both implementations

Page 25: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Static methods and variables• Variables such as radius in the Circle example are called

instance variables. They belong to each instance.• A static variable is shared among all instances of a class. Only

one copy of a static variable for all objects of the class. • Static variables are also called class variables.• Similarly, there is the concept of static methods. • We do not have to instantiate an object of a class in order to

invoke a static method. Static methods are invoked through the class name.

• Static methods cannot access instance variables.• To declare static variables and methods, we use the static

modifier. • Be careful not to over use static variables to lose the ideas of

objects!

Page 26: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity and Example• Why are static variables needed?• Scenario: want to count the number of objects

created from a particular class– It wouldn’t make sense for this information to be

associated with individual instances – We only want to keep one copy of this variable; and it

should be linked to the class– Use a static variable numOfObjects to track the number of

objects created. – To record the number of objects being generated, we

increment the numOfObjects variable each time a new instance is created. This is done in the constructors.

Page 27: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity (may skip)

• Complete unit 6 student activity 6.5

Page 28: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Methods overloading

• Method overloading allows us to define two or more methods that have the same method name, but different parameter list within the same class.

• Note that you cannot overload methods based on different return type.

• Overloading methods can make programs clearer and more readable. Methods that perform closely related tasks should be given the same name.

Page 29: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Example of method overloadingpublic class MethodOverloading {

int maxNum(int i, int j){

if (i>j) return i;

else return j;

}

int maxNum(int i, int j, int k){

int tmp=maxNum(i,j);

return maxNum(tmp,k);

}

… …

MethodOverloading test=new MethodOverloading(); int I = test.maxNum(5,3); int j = test.maxNum(5,3,6);……

Page 30: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Exception handling (may skip)

• Examples of causes of exceptions• Different ways of handling exceptions– Not handling the exception at all– Handling where it occurs using try-catch– Handling exception at a different point

Page 31: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Examples of causes exceptions

• Typical examples include: – division by zero, – array index out of bounds,– file does not exist,– null pointer and– I/O exception.

• In Java, these, and many other such, unusual situations are defined as exception classes.

• The programmers can also define their own exception classes to capture new exceptional situations.

Page 32: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Not handle the exceptions

• do not handle it , the program terminates with an exception message telling us what exception occurred and where it occurred.

Page 33: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Example (Student activity 6.6)class SomeExceptions {

public int divide(int m){

Scanner in=new Scanner(System.in);

int n=in.nextInt();

// get the value of the divisor

return m/n;

}

}

public class IllustrateException {

public static void main(String [] args) {

SomeExceptions myProg = new SomeExceptions();

System.out.println(myProg.divide(100));

}

}

Page 34: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Handling exception where it occurs: the try-catch statement

• The try-catch statement identifies a block of statements that may produce one or more exceptions.

• One or more catch clauses should follow a try block. The catch clauses define how to handle each type of exception that may occur in the try block.

• Each catch clause is called an exception handler.

Page 35: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Revised example (student activity 6.7)

class SomeException2 {

int maxInt=999999999;

public int divide(int m){

Scanner in=new Scanner(System.in);

int n=in.nextInt();

try{

return m/n;

} catch (ArithmeticException e) {

System.out.println("An exception has occurred.");

System.out.println("A big number is returned as a default.");

return maxInt;

}

}

}

Page 36: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Handling exception at a different point

• If an exception is not caught and handled where it occurs, control is immediately returned to the place that invoked the method, e.g.– if the divide method does not provide any

mechanism to catch and handle the arithmetic exception, the control will be returned to the main program where it calls myProg.divide(100).

• We can design programs so that the exception is caught and handled at this outter layer using try-catch statement

Page 37: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Revise example

public class IllustrateException3 {

public static void main(String [] args) {

SomeExceptions myProg = new SomeExceptions();

try {

System.out.println(myProg.divide(100));

} catch (ArithmeticException e){

System.out.println("exception happened,

caught at outer level.");

}

}

}

Page 38: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Student activity

• Complete unit 6 student activities 6.6 and 6.7 (exception)

• Multiple choice questions

Page 39: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

An integrate case study

• Go through the case study• Go through the design (note with voice over)• Student activity• Go through outline and solution

Page 40: Unit 6: Object-oriented Programming: Objects and Classes Jin Sa

Summary

• how to define classes; • how to create objects; • what is an object reference; • how to use visibility modifiers to achieve the right level of

encapsulation; • how to pass objects as parameters to a method and how to

return an object as a result; • array of objects;• static method and variables;• exception handling