28
CPCS204: Data Structure 1 Dr. Sahar Shabanah Lecture 2

Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

Embed Size (px)

Citation preview

Page 1: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

CPCS204: Data Structure 1Dr. Sahar Shabanah

Lecture 2

Page 2: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

2

Outline

Review of O-O ConceptsInheritanceInterfacesPolymorphismCastingGenericsJava DocumentationExceptions

Page 3: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

3

InheritanceThe capability of a class to use the properties

and methods of another class while adding its own functionality.

Example: employee records system. A generic employee class with states and actions

that are common to all employees. (parent, super, or base class)

Specific classes could be defined for salaried, commissioned and hourly employees. (children, subclasses or derived classes)

Advantage: enhances the ability to reuse code as well as making design a much simpler and cleaner process.

Page 4: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

4

Inheritanceextends keyword set the relationship between a

parent and a child.public class GraphicsBox extends Box

GraphicsBox inherits all the properties of Box and can now add its own properties and methods as well as override existing methods.

Overriding: creating a new set of method statements for the same method signature.// define position locations private int left, top;// override a superclass method public int displayVolume() { System.out.println(length*width*height); System.out.println("Location: "+left+", "+top);

}

Page 5: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

5

super & thissuper: allows the reuse of the superclass

constructor and methods by the subclasses

this: used to distinguish between the object's property and the passed in parameterGraphicsBox(l,w,h,left,top) {

super (l,w,h); //must come first in constructor

this.left=left; this.top=top; } public void showObj() { System.out.println(super.showObj()

+"more"); }

Page 6: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

6

Object ClassThe Object class is the highest superclass

(ie. root class) of Java. All other classes are subclasses (children

or descendants) of the Object class. The Object class includes methods such

as:clone(), equals(), copy(Object src), finalize(), getClass(), hashCode(),notify(), notifyAll(), toString(), wait()

Page 7: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

7

Concrete & Abstract ClassesFinal classes: cannot be extendedConcrete superclass: instance objects can be

created from Abstract superclass: does not allow objects of its

prototype to be created. Abstract methods: methods with no body

specification, must provided by the subclasses.public abstract class Animal{ // class is abstract

private String name; public Animal(String nm) // constructor method { name=nm; } public String getName() // regular method { return (name); } public abstract void speak(); //abstract method, no{} }

Page 8: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

8

Interfaces Similar to abstract classes but all methods are

abstract and all properties are static final. can be inherited (sub-interface) using extends.No multiple inheritance for classes, can

implements only for interfaces. Advantages, Interfaces are used to:

tie elements of several classes together. separate design from coding as class method

headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase.

set up unit testing frameworks.

Page 9: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

9

ExampleWorking interface for the subclasses of

Animals, method work(), that method must be

defined in any class using the Working interface:public interface Working{ public void work();}

When a class uses an interface, it reference the interface with the phrase implements Interface_list.

Interface_list is one or more interfaces as multiple interfaces are allowed.

Page 10: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

10

Example cont.Any class that implements an interface must

include code for all methods in the interface. public class WorkingDog extends Dog implements Working {

public WorkingDog(String nm) { super(nm); // builds ala parent } public void work() // this method specific to WorkingDog

{ speak(); System.out.println("I can herd sheep and cows"); }

}

Page 11: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

11

PolymorphismThe capability of an action or method to do

different things based on the object that it is acting upon.

The third basic principle of object oriented programming.

Three types:1. Overloaded methods are methods with the same

name signature but either a different number of parameters or different types in the parameter list.

2. Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used.

3. Dynamic method binding.

Page 12: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

12

Dynamic method bindingThree subclasses (Cow, Dog and Snake) have been created

based on the Animal abstract class, each having their own speak() method.public class AnimalReference{ public static void main(String args[]) Animal ref // set up var for an Animal

Cow aCow = new Cow("Bossy"); // makes specific objects

Dog aDog = new Dog("Rover"); Snake aSnake = new Snake("Ernie"); // now reference each as an Animal ref = aCow; ref.speak(); //speak of Cow ref = aDog; ref.speak();// speak of Dog ref = aSnake; ref.speak();// speak of Snake}

Page 13: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

13

Dynamic method bindingArray of objects example

public class AnimalArray{ public static void main(String args[]) Animal ref[] = new Animal[3]; // assign space for array

Cow aCow = new Cow("Bossy"); // makes specific objects

Dog aDog = new Dog("Rover"); Snake aSnake = new Snake("Earnie");

// now put them in an array ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

// now demo dynamic method binding for (int x=0;x<3;++x) { ref[x].speak(); }}

Page 14: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

14

Casting Widening Conversions (T converted into a

“wider” type U), if:U superclass of T, U superinterface of T, T

implements UEx: Integer extends NumberInteger i=new Integer(3);Number n=i; // widening from Integer to Number

Narrowing conversions (T converted into a “narrower” type S), if:S is a subclass of T, S is a subinterface of T, S

implements TNumber n=new Integer(2); //widening from Integer to NumberInteger i=(Integer) n; //narrowing from Number to Integer

Page 15: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

15

Casting ExceptionsExample

Number n; Integer I;n= new Integer(3);i=(Integer)n;n=new Double(3.14);i=(Integer) n; //this is illegal

Solution: (object-type) instanceof (refrence-type)n=new Double(3.14); if ( n instanceof Integer)i=(Integer) n; //this will not attempted

Page 16: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

16

Casting with Interfacespublic interface Person{ public boolean equalTo(Person other); public String getName();}public Student implements Person{ String id, name; int age; public Student(String I, String n, int a){id=I;name=n;age=a;}

public boolean equalTo(Person other){//from Person Interface

Student otherStudent=(Student)other;//cast Person to Student

return (id.equals(otherStudent.getID()); }}

Page 17: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

17

Casting & Dynamic BindingWhen using a superclass array to hold many instances

of subclass objects, one can only access properties and methods that are in the superclass (ie. common to all).

By casting an individual instance to its subclass form, one can refer to any property or method.

make sure the cast is valid by using the instanceof operator. if (ref[x] instanceof Dog) // ok right type of object

{

Dog doggy = (Dog) ref[x]; // cast current instance to

subclass

doggy.someDogOnlyMethod();

}

Page 18: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

18

GenericsGeneric programming refers to writing code that

will work for many types of data. The Java collections framework promotes generic

programming by applying a unifying philosophy that adds operational functionality, and dynamic growth to object classes.

Unification is accomplished through interfaces that each collection object inherits.

Various types of objects may be handled in a similar manner within collection framework classes.

Functionality such as searches, sorts, insertion and deletion use highly efficient algorithms.

Page 19: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

19

Collection Interfaces

Page 20: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

20

Collections ClassesConcrete collection classes implement the

appropriate interfaces and incorporate advanced and optimized data structures for programming ease.

The main collection classes include:ArrayList implements List and is very similar to arrays

but is dynamic (ie. its size does not have to be declared at compile time).

HashSet implements the Set interface and uses a hash table for efficient storage.

LinkedList implements the appropriate data structure which can be traversed and nodes inserted and deleted.

TreeSet implements a sorted set using a binary tree for storage, allowing rapid access to list elements.

Page 21: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

21

Java Documentation classesJAVA API (Application Programming Interface):

http://download-llnw.oracle.com/javase/1.5.0/docs/api/The Java API includes several predefined class packages

(class libraries): Applets java.applet, language extensions java.lang, utilities java.util, formatters java.text, file streams java.io, GUIs java.awt and

javax.swing, database management java.sql

import is used to access classes from the libraries (except for java.lang).

Example classes of java.lang: Object, System, Math, String, Number, Integer, Double, Boolean,…….

Exceptions examples of java.lang: java.lang.ArithmeticException, java.lang.ArrayIndexOutOfBoundsException, java.lang.ClassCastExceptio

Page 22: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

22

ExceptionsAn exception is an event, which occurs

during the execution of a program, that disrupts the normal flow of the program's instructions.

When an error occurs within a method, the method creates an object and hands it off to the runtime system.

The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.

Creating an exception object and handing it to the runtime system is called throwing an exception.

Page 23: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

23

The Exception Class HierarchyExceptions classes are related

by inheritance, forming a hierarchy

All error and exception classes are descendents of the Throwable class

A programmer can define an exception by extending the Exception class or one of its descendants

The parent class used depends on how the new exception will be used

Page 24: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

24

Three Kinds of Exceptions1. Errors:

These are exceptional conditions that are external to the application (hardware failure), and that the application usually cannot anticipate or recover from.

not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

2. Runtime exception:These are exceptional conditions that are internal to the

application, and that the application usually cannot anticipate or recover from.

These usually indicate programming bugs, such as logic errors or improper use of an API.

Page 25: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

25

Three Kinds of Exceptions3. Checked exceptions:

these are exceptional conditions that a well-written application should anticipate and recover from.

must be enclosed by either of the following:1. A throws clause to pass the exception up the stack

to let another method to handle it:

public void writeList() throws IOException{ 2. A try statement that catches and handles the

exception

Page 26: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

26

Exception HandlingAfter a method throws an exception,

the runtime system searches the call stack (ordered list of methods that had been called so far) for a method that contains a block of code that can handle the exception (exception handler)

When an appropriate handler is found, the runtime system passes the exception to the handler (catch the exception).

If no handler founds, the runtime system (and, consequently, the program) terminates.

Page 27: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

27

try-catch syntax try: tests a section of code, if an exception error occurs. catch traps and handles the error, any number of catches

can be set up for various exception types. finally provides a block of code that is always performed.try{

// tested statement(s);}catch (ExceptionName e1){// trap handler statement(s);}catch (ExceptionName e2){ // any number of catch statementsSystem.out.println("Exception: " + e2);

}finally{// always executed block}

Page 28: Dr. Sahar Shabanah Lecture 2. Outline Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions 2

28

Throw statement Exceptions are thrown using the throw statement

Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown

public class OutOfRangeException extends Exception

{

// Sets up the exception object with28 message.

OutOfRangeException (String message)

{super (message);}

}

OutOfRangeException problem =

new OutOfRangeException ("Input is out of range.");

-----

-----

if (value < MIN || value > MAX) throw problem;