Upgrade to Pro — share decks privately, control downloads, hide ads and more …

lecture10.pdf

Avatar for William Albritton William Albritton
August 27, 2014
88

 lecture10.pdf

Avatar for William Albritton

William Albritton

August 27, 2014
Tweet

Transcript

  1. Interface • An interface is a list of method prototypes

    used to enforce the naming of method prototypes for a class • When a class implements a particular interface, this ensures that designers of the class and users of the class are using the same method names
  2. Interface • For example, the panel of buttons on an

    ice machine is the ice machine’s interface • Syntax for an interface: public interface InterfaceName{ methodPrototypes1(); methodPrototypes2(); methodPrototypesN(); }
  3. Interface • Another way to think of an interface is

    as a “contract” for methods • The class that implements the interface must fulfill the interface “contract” by defining methods with the same method prototype (same method name, return type, and parameter types) as the interface
  4. Interface • Syntax for a class definition that implements an

    interface: public ClassName implements InterfaceName{ //Must have code for all the //methods in the interface. }
  5. Interface Example • See file FractionInterface.java  Has the method

    prototypes for 9 methods: add(), subtract(), multiply(), divide(), reduceToLowestTerms(), getNumerator(), getDenominator(), setNumerator(), setDenominator()
  6. Implementation Example • See file Fraction.java  Implements the 9

    methods of FractionInterface.java, so it has the code for these 9 methods  Each method prototype has the same name, return type, and parameters as the method prototypes listed in FractionInterface.java
  7. Using Interfaces • Just like using a Class name to

    declare variables, you can use an Interface name when declaring variables • Remember that a declaration is on the left side of the equals sign when initializing a variable
  8. Using Interfaces • Visualize it as just drawing a box

    and assigning it the value that is on the right hand side of the assignment operator f1 Numerator denominator 2 5
  9. Using Interfaces • The reason why we can use the

    Interface name instead of the Class name for the declaration is that the Class or Interface name is used to tell the compiler what methods can be legally used by a particular variable
  10. Using Interfaces • You can also use an interface when

    declaring a parameter, or as a return type
  11. Using Interfaces • Syntax for method definition: public InterfaceName methodName(InterfaceName

    parameterName){ . . . //method’s code } • Example method definition: public FractionInterface add (FractionInterface f2){ . . . //method’s code }
  12. Using Interfaces • FractionCalculator.java method call: FractionInterface fraction3 = fraction1.add(fraction2);

    • Fraction.java method definition: public FractionInterface add (FractionInterface f2){ . . . //method’s code } • Both fraction2 and f2 point to the same object (call by reference)
  13. Using Interfaces • Visualize as two boxes pointing to the

    same balloon f2 numerator denominator 2 5 fraction2
  14. Using Interfaces • FractionCalculator.java method call: FractionInterface fraction3 = fraction1.add(fraction2);

    • Fraction.java method definition: public FractionInterface add (FractionInterface f2){ FractionInterface result=new Fraction(n3,d3); return result; }
  15. Using Interfaces • Visualize as two boxes pointing to the

    same balloon fraction3 numerator denominator 4 5 result
  16. Inheritance • Inheritance is a way for a class to

    reuse the methods and data fields of an already existing class • Don’t have to “reinvent the wheel” (start from the beginning) when creating a new class
  17. Inheritance • Inheritance is helpful for 1.Organizing code 2.Compiling code

    (large programs broken down into smaller parts) 3.Debugging code 4.Improving code
  18. Inheritance • When you use inheritance, you have a superclass

    and a subclass • A superclass (base class) is the class from which other classes will be built • A subclass (derived class) is a new class built from an existing class
  19. Inheritance • The subclass inherits (can use) the data fields

    and methods of its superclass • A subclass can also create its own data fields and methods, which do not exist in the superclass
  20. How to Create a Subclass • Step #1: The subclass

    must inherit from a superclass • On the first line of the class definition, use keyword “extends” followed by the name of the superclass
  21. How to Create a Subclass • See IllegalFractionException.java file for

    the example code public class IllegalFractionException extends RuntimeException{…} • Our IllegalFractionException class inherits the methods and data fields of superclass RuntimeException
  22. How to Create a Subclass • Step #2: Must call

    the superclass’s constructor • Use the keyword “super” to call superclass’s constructor super(message); • If not done, the compiler will automatically call this constructor super();
  23. Creating Exception Classes • You can use inheritance to create

    your very own exception class! • Choose superclass Exception or RuntimeException to determine if exception must be handled or not • Personally, I like to use RuntimeException as the superclass
  24. Throwing Exceptions • A throw statement is a statement that

    begins exception propagation • Syntax for throwing an exception: throw new ExceptionName("msg"); • If an exception is thrown, code following the throws statement will NOT be executed
  25. Throwing Exceptions • If a method contains a throw statement,

    the exception’s type (exception's class name) must be listed in the method’s prototype • Syntax: public void myMethod() throws MyException{ /* code */ throw new MyException(); }
  26. Throwing Exceptions • See the constructor in the example code

    Fraction.java public Fraction(Integer n, Integer d) throws IllegalFractionException{ //method code if(denominator.equals(0)){ throw new IllegalFractionException( "Cannot have 0 as the denominator!"); }
  27. Exception Propagation • If an exception is thrown, but not

    caught within a method:  Then the exception propagates to the method that called this method  The process continues, until the exception is propagated to the main method
  28. Exception Propagation • If an exception is thrown, but not

    caught within a method:  If it is not caught within the main method, the program terminates
  29. Exception Propagation • If IllegalFractionException is thrown in the setDenominator()

    method, it is caught in the main method of class FractionCalculator • Run the program and enter 0 (zero) as the denominator to see the result • Also run DoNotCatch.java to see what happens if the exception is not caught
  30. How to Create a Subclass • Step #3: Replace the

    keyword “private” with the keyword “protected” for all data fields in the superclass • We only have to do this for subclasses that we have created ourselves • We cannot change the code for classes in the Java API
  31. Access Modifiers • Access modifiers are used to control the

    scope of classes, methods and variables • Three (3) kinds of access modifiers  public: visible to the class and its subclasses and client
  32. Access Modifiers • Three (3) kinds of access modifiers 

    protected: visible only to the class and its subclasses  private: visible only to the class
  33. How to Create a Subclass • Here is another example

    to give you insights into inheritance • Superclass: Name.java • Subclass: ThreeNames.java
  34. How to Create a Subclass • To inherit from a

    superclass, use keyword “extends” and superclass’s name public class ThreeNames extends Name{ ... } • To call the superclass’s constructor, use the keyword “super” super(aFirst, aLast);
  35. Example Code • Superclass: Name • Class Name is composed

    of following two (2) String objects: protected String first; protected String last;
  36. Example Code • Subclass: ThreeNames • Class ThreeNames inherits from

    class Name public class ThreeNames extends Name{. . .}
  37. Example Code • Class ThreeNames is composed of data fields

    first and last, inherited from class Name, and a third string private String middle;
  38. Override • Overriding is when a subclass redefines (rewrites the

    code to) a method of its superclass • Used to create a method that is more appropriate to the implementation of the subclass
  39. Override • Overriding takes place when the methods of the

    superclass and subclass have the same method prototype • In other words, the first line of both methods in both classes is the same, but the code in the body of the methods is different
  40. Override Example • Methods in both Name and ThreeNames that

    use overriding: toString(), initials() • Methods inherited from Name: getFirstName(), getLastName(), setFirstName(), setLastName() • Additional methods in ThreeNames: getMiddleName(), setMiddleName()
  41. Polymorphism • Polymorphism is the ability of objects of different

    classes related by inheritance to respond differently to the same method call • Literally means “many forms” • Polymorphism only works with overridden methods
  42. Polymorphism • A variable declaration of a superclass can contain

    the address to any superclass or subclass object • For overridden methods, the method that is called depends on the object’s class, but not on the class of the variable declaration
  43. Polymorphism Syntax • Superclass variable initialization syntax: SuperClass variableName1 =

    new SuperClass(); • Subclass variable initialization syntax: SuperClass variableName2 = new SubClass();
  44. Polymorphism Syntax • Superclass method call syntax: SuperClass variableName1 =

    new SuperClass(); variableName1.overloadedMethod(); //call to SuperClass’s method • Subclass method call syntax: SuperClass variableName2 = new SubClass(); variableName2.overloadedMethod(); //call to SubClass’s method
  45. Polymorphism Example • Method call to Name’s initials() Name name1

    = new Name("Fujiko", "Suzuki"); System.out.println(name1.initials()); //Output is "F. S."
  46. Polymorphism Example • Method call to ThreeName’s initials() name1 =

    new ThreeNames("Jeff", "Masao", "Suzuki"); System.out.println(name1.initials()); //Output is "J. M. S."
  47. OOP • OOP has three (3) basic parts 1. Classes

    (create objects) 2. Inheritance (create subclasses) 3. Polymorphism (using the same method call to different classes that are related by inheritance)
  48. Task Manager • Before the next class, you need to:

    1.Do the assignment corresponding to this lecture 2.Email me any questions you may have about the material 3.Turn in the assignment before the next lecture 4.Smell the flowers!