280 likes | 394 Views
CPCS204: Data Structure 1. Dr. Sahar Shabanah Lecture 2. Outline. Review of O-O Concepts Inheritance Interfaces Polymorphism Casting Generics Java Documentation Exceptions. Inheritance.
E N D
CPCS204: Data Structure 1 Dr. Sahar Shabanah Lecture 2
Outline • Review of O-O Concepts • Inheritance • Interfaces • Polymorphism • Casting • Generics • Java Documentation • Exceptions
Inheritance • The 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.
Inheritance • extends keyword set the relationship between a parent and a child. public class GraphicsBoxextends 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 intdisplayVolume() { System.out.println(length*width*height); System.out.println("Location: "+left+", "+top); }
super & this • super: 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 parameter GraphicsBox(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"); }
Object Class • The 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(Objectsrc), • finalize(), getClass(), hashCode(), • notify(), notifyAll(), toString(), • wait()
Concrete & Abstract Classes • Final classes: cannot be extended • Concrete 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{} }
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.
Example • Working 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 implementsInterface_list. • Interface_list is one or more interfaces as multiple interfaces are allowed.
Example cont. • Any class that implements an interface must include code for all methods in the interface. public class WorkingDogextends 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"); } }
Polymorphism • The 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: • Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. • Overridden methods are methods that are redefined within an inherited or subclass. They have the same signature and the subclass definition is used. • Dynamic method binding.
Dynamic method binding • Three 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(Stringargs[]) 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 }
Dynamic method binding • Array of objects example public class AnimalArray{ public static void main(Stringargs[]) 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 (intx=0;x<3;++x) { ref[x].speak(); } }
Casting • Widening Conversions (T converted into a “wider” type U), if: • U superclass of T, U superinterface of T, T implements U • Ex: Integer extends Number Integer 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 T Number n=new Integer(2); //widening from Integer to Number Integer i=(Integer) n; //narrowing from Number to Integer
Casting Exceptions • Example 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 ( ninstanceof Integer) i=(Integer) n; //this will not attempted
Casting with Interfaces public interface Person { public booleanequalTo(Person other); public String getName(); } public Student implements Person { String id, name; int age; public Student(String I, String n, inta){id=I;name=n;age=a;} public booleanequalTo(Person other){//from Person Interface Student otherStudent=(Student)other;//cast Person to Student return (id.equals(otherStudent.getID()); } }
Casting & Dynamic Binding • When 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(); }
Generics • Generic 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.
Collections Classes • Concrete 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.
Java Documentation classes • JAVA 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
Exceptions • An 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.
The Exception Class Hierarchy • Exceptions 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
Three Kinds of Exceptions • 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. • 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.
Three Kinds of Exceptions • Checked exceptions: • these are exceptional conditions that a well-written application should anticipate and recover from. • must be enclosed by either of the following: • A throws clause to pass the exception up the stack to let another method to handle it: public void writeList() throws IOException{ • A try statement that catches and handles the exception
Exception Handling • After 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.
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 statements System.out.println("Exception: " + e2); }finally{// always executed block }
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;