Unit 6 object oriented programming objects and classes
Download
1 / 40

Unit 6: Object-oriented Programming: Objects and Classes - PowerPoint PPT Presentation


  • 60 Views
  • Uploaded on
  • Presentation posted in: General

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha

Download Presentation

Unit 6: Object-oriented Programming: Objects and Classes

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


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.


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.


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.


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 value

    void setRadius(double newR){

    radius=newR;

    }

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

    • findArea().


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().


Creating objects – new(see TestSimpleCircle)

  • To create an object, we use the new operator.

    • new Circle();

    • new Circle(2.5);


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


More about object references

c=new Circle();


More about object references (2)


Student Activity

  • Complete Unit 6 student activity 6.1


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.


Visibility modifiers (2)


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;

    }


Student activity (may skip)

  • Complete unit 6 student activity 6.2


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

    }


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 method

    public static void main(String[] args) {

    Circle c1= new Circle(2.0);

    Circle c2 = c1.biggerCircle();

    double r = c2.getRadius();

    }


Student activity

  • Complete unit 6 student activity 6.3


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

    }


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

}

}

… …


Student activity

  • Complete unit 6 student activity 6.4.


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


An example of ArrayList

public 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");

}

}

… …

}


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


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!


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.


Student activity (may skip)

  • Complete unit 6 student activity 6.5


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.


Example of method overloading

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

……


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


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.


Not handle the exceptions

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


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

}

}


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.


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;

}

}

}


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


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.");

}

}

}


Student activity

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

  • Multiple choice questions


An integrate case study

  • Go through the case study

  • Go through the design (note with voice over)

  • Student activity

  • Go through outline and solution


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


ad
  • Login