You can write your code to talk to the parent class and know that all the child

You can write your code to talk to the parent class

This preview shows page 9 - 15 out of 18 pages.

You can write your code to talk to the parent class and know that all the child classes will work correctly using the same code. Easy to maintain your program class Vet { public void giveShot(Animal a) { Dog makeNoise() Hippo makeNoise()Animal makeNoise() a.makeNoise(); } } class PetOwner { public void main() { Vet v = new Vet() ; Dog d = new Dog(); Hippo h = new Hippo() ; v. giveShot (d) ; v. giveShot (h); }} 9
Background image
Polymorphism and arrays x class A { public int getVal() { return 1;} A B B C } class B extends A { public int getVal() { return 1+super.getVal(); } } class C extends B { public int getVal() { return 1+super.getVal(); } } public class poly_arrays{ public static void main(String[] args) { A[] x = new A[4]; x[0] = new A(); x[1] = new B(); x[2] = new B(); x[3] = new C(); int sum = 0; for (int i=0; i<x.length; i++) sum+=x[i].getVal(); System.out.println(sum); }} 10
Background image
Polymorphism via Inheritance Polymorphism via Interfaces <Interface> Speaker Speak()Philosopher Speak() pontificate() Dog Speak()The interface name, speaker, can be used to declare an object reference variable. Speaker guest = new Philospher(); The guest reference can be used to point to any object of any class that implements the Speakerinterface The version of speak depends on the type of object that current is referencing guest.speak(); 11
Background image
Exceptions An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions The Java language uses exceptions to provide error-handling capabilities for its programs. Exceptions are represented as classes in Java. (Hardware or System) ThrowableError ExceptionLinkageError VirtualMachineErrorRunTimeExceptionArithmeticExceptionIndexOutOfBoundsExceptionIllegalAccessExceptionNegativeArraySizeException12
Background image
A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program Exception: Handle Where It OccursException is represented as an object in Java. They are thrownby a program, and may be caughtand handledby another part of the program 13
Background image
The tryand catchStatementtry { // Code that might generate exceptions } catch(Type1 id1) { // Handle exceptions of Type1 } catch(Type2 id2) { // Handle exceptions of Type2 } catch(Type3 id3) { // Handle exceptions of Type3 } // etc...
Background image
Image of page 15

You've reached the end of your free preview.

Want to read all 18 pages?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture