Overriding Refined

Embed Size (px)

Citation preview

  • 7/31/2019 Overriding Refined

    1/43

    OVERRIDING/OVERLOADIN

    G

    Srinivas

  • 7/31/2019 Overriding Refined

    2/43

    EXAM OBJECTIVES

    Given a code example, determine if amethod is correctly overriding oroverloading another method, and identifylegal return values (including covariantreturns), for the method.

    Given a scenario, develop code that

    declares and/or invokes overridden oroverloaded methods and code thatdeclares and/or invokes superclass,overridden, or overloaded constructors.

  • 7/31/2019 Overriding Refined

    3/43

    OVERRIDING

    What is overriding?

    The child class provides alternativeimplementation for parent class method.

    The key benefit of overriding is the ability todefine behavior that's specific to a particularsubclass type.

    Overridden method: In the superclass.

    Overriding method: In the subclass.

  • 7/31/2019 Overriding Refined

    4/43

    METHOD OVERRIDING

    Example: publicclass Car { publicvoidmaxSpeed() { System.out.println("Max speed is 60

    mph");

    } }

    class Ferrari extends Car { publicvoidmaxSpeed() { System.out.println("Max speed is 120

    mph"); } publicvoidmsc(){} }

  • 7/31/2019 Overriding Refined

    5/43

    publicclass TestCar

    {

    publicstaticvoidmain(String args[]) {

    Ferrari f=new Ferrari();

    f.maxSpeed();

    }

    OR

    publicstaticvoidmain(String args[])

    {

    Car f=new Ferrari(); f.maxSpeed();

    }

    }

  • 7/31/2019 Overriding Refined

    6/43

    In the preceding code, the test class uses aCar reference to invoke a method on aFerrari object.

    This is possible because Ferrari IS-A

    Car. The compiler will allow only methods in class

    Car to be invoked when using a reference toa Car.

    Car f=new Ferrari();

    f.msc();

    JVM sees the real object at the other end of

  • 7/31/2019 Overriding Refined

    7/43

    RULES FOR METHOD

    OVERRIDING

    EXACT argument list matching.

    publicclass Car

    {

    publicvoidmaxSpeed(int speed)

    {

    System.out.println("Max speed is +speed+

    mph"); }

    }

    class Ferrari extends Car

    {

    publicvoidmaxSpeed(float speed)

    { System.out.println("Max speed is +speed+

    mph");

    }

    publicvoidmsc(){}

    }

  • 7/31/2019 Overriding Refined

    8/43

    RULES FOR METHOD

    OVERRIDING

    The return type must be the same as, or a subtype of, the returntype declared in the original overridden method in the superclass.

    class Alpha

    {

    Alpha doStuff(char c)

    {

    returnnew Alpha();

    }

    }

    class Beta extends Alpha

    {

    Beta doStuff(char c)

    {

    returnnew Beta();// legal override in Java 1.5

    }

    }

  • 7/31/2019 Overriding Refined

    9/43

    RULES FOR METHOD

    OVERRIDING

    The access level can't be more restrictive than the overriddenmethod's.

    publicclass Car

    {

    publicvoidmaxSpeed()

    {

    System.out.println("Max speed is 60 mph");

    }

    }

    class Ferrari extends Car

    {

    privatevoidmaxSpeed() {

    System.out.println("Max speed is 120 mph");

    }

    publicvoidmsc(){}

    }

  • 7/31/2019 Overriding Refined

    10/43

    RULES FOR METHOD

    OVERRIDING

    The access level CAN be less restrictive than that of the overriddenmethod.

    publicclass Car

    {

    protectedvoidmaxSpeed()

    {

    System.out.println("Max speed is 60 mph");

    }

    }

    class Ferrari extends Car

    {

    publicvoidmaxSpeed() {

    System.out.println("Max speed is 120 mph");

    }

    publicvoidmsc(){}

    }

  • 7/31/2019 Overriding Refined

    11/43

    RULES FOR METHOD

    OVERRIDING

    Possible only through inheritance.

    publicclass Car

    {

    protectedvoidmaxSpeed()

    {

    System.out.println("Max speed is 60 mph");

    }

    }

    class Ferrari

    {

    publicvoidmaxSpeed()

    { System.out.println("Max speed is 120 mph");

    }

    publicvoidmsc(){}

    }

  • 7/31/2019 Overriding Refined

    12/43

    RULES FOR METHOD

    OVERRIDING The overriding method CAN throw any

    unchecked (runtime) exception, regardless ofwhether the overridden method declares theexception.

    An uncheckedexception, also calledruntimeexception, is detected only atruntime.

    Examples ofuncheckedexceptions:

    o ArithmeticExceptiono ArrayIndexOutOfBoundsException

    o NullPointerException

    o NumberFormatException

  • 7/31/2019 Overriding Refined

    13/43

    publicclass NoRunExc

    {

    publicvoiddivideBy()

    {

    int result= 100/1;

    System.out.println(result);

    }

    publicstaticvoidmain(String[] args)

    { NoRunExc n=new NoRunExc();

    n.divideBy();

    NoRunExc r=new RunExc();

    r.divideBy();

    }

    }

    class RunExc extends NoRunExc

    { publicvoiddivideBy() throws ArithmeticException

    {

    int result= 100/0;

    System.out.println(result);

    }

    }

  • 7/31/2019 Overriding Refined

    14/43

    RULES FOR METHOD

    OVERRIDING The overriding method must NOT throw

    checked exceptions that are new orbroader than those declared by theoverridden method.

    A checkedexceptionis an exceptionthat is checked at compile time. Thecompiler will complain if a checkedexception is not handled appropriately.

    Examples ofcheckedexceptions: IOException

    FileNotFoundException

    EOFException

  • 7/31/2019 Overriding Refined

    15/43

    RIGHT import java.io.*;

    publicclass Exc

    {

    publicvoidopenFile() throws IOException

    {

    try

    {

    FileWriter fw=new FileWriter("Filename.txt");

    }

    catch (IOException e)

    {

    e.printStackTrace();

    }

    }

    }

    class Exc2 extends Exc

    {

    publicvoidopenFile() throws FileNotFoundException

    {

    try

    {

    FileReader fw=new FileReader("Filename.txt"); }

    catch (FileNotFoundException e)

    {

    e.printStackTrace();

    }

    }

    }

  • 7/31/2019 Overriding Refined

    16/43

    WRONG import java.io.*;

    publicclass Exc

    {

    publicvoidopenFile() throws FileNotFoundException

    {

    try

    {

    FileWriter fw=new FileWriter("Filename.txt");

    }

    catch (IOException e)

    {

    e.printStackTrace();

    }

    }

    }

    class Exc2 extends Exc

    {

    publicvoidopenFile() throws IOException

    {

    try

    { FileReader fw=new FileReader("Filename.txt");

    }

    catch (FileNotFoundException e)

    {

    e.printStackTrace();

    }

    }

    }

  • 7/31/2019 Overriding Refined

    17/43

    RULES FOR METHOD

    OVERRIDINGAn overriding method doesn't have to

    declare any exceptions that it will

    never throw, regardless of what the

    overridden method declares.

  • 7/31/2019 Overriding Refined

    18/43

    import java.io.*;

    publicclass Exc

    {

    publicvoidopenFile() throws IOException

    {

    try

    {

    FileReader fw=new FileReader("Filename.txt"); }

    catch (FileNotFoundException e) {

    e.printStackTrace();

    }

    }

    }

    class Exc2 extends Exc

    { publicvoidopenFile()

    {

    System.out.println(Ill open the file later");

    }

    }

  • 7/31/2019 Overriding Refined

    19/43

    RULES FOR METHOD

    OVERRIDINGYou cannot override a method markedfinal.

    You cannot override a method marked

    static.

  • 7/31/2019 Overriding Refined

    20/43

    What happens here?

    publicclass Car { public finalvoidmaxSpeed() { System.out.println("Max speed is 60mph");

    } }

    class Ferrari extends Car { publicvoidmaxSpeed() {

    System.out.println("Max speed is 120mph"); } publicvoidmsc(){} }

  • 7/31/2019 Overriding Refined

    21/43

    Invoking a Superclass Version of

    an Overridden MethodUse the code in the overridden

    method.

    Also add extra features in overriding

    method.

  • 7/31/2019 Overriding Refined

    22/43

    publicclass Car {

    protected voidmaxSpeed()

    {

    System.out.println("Max speed is 60 mph");

    }

    }

    class Ferrari extends Car

    {

    publicvoidmaxSpeed()

    {

    super.maxSpeed(); System.out.println("I can race");

    }

    }

  • 7/31/2019 Overriding Refined

    23/43

    Introduction to overloading

    Same name, different arguments.Code deals with different argument types

    rather than forcing the caller to doconversions prior to invoking yourmethod.

    It CAN have a different return type.

    Argument list MUST be different.

    Access modifier CAN be different.New exceptions can be declared.

    A method can be overloaded in the same

    class or in a subclass.

  • 7/31/2019 Overriding Refined

    24/43

    In same class

    publicclass Sort {

    publicvoidsort2(int[] a )

    {

    //Program to sort integers }

    publicvoidsort2(String[] a )

    { //Program to sort Strings

    }

  • 7/31/2019 Overriding Refined

    25/43

    publicclass TestSort {

    publicvoidarr()

    {

    int[] a={3,8,6,1,2};

    String[] s={"Sachin","Sourav","Dravid"};

    Sort s=new Sort();

    s.sort2(a); s.sort2(s);

    }

    publicstaticvoidmain(String[] args)

    { TestSort t=new TestSort();

    t.arr();

    }

    }

  • 7/31/2019 Overriding Refined

    26/43

    In different classes

    publicclass Sort {

    publicvoidsort2(int[] a )

    {

    //Program to sort integers

    }

    }

    class FloatSort extends Sort

    {

    publicvoidsort2(double[] a ) {

    //Program to sort floats

    }

  • 7/31/2019 Overriding Refined

    27/43

    publicclass TestSort {

    publicvoidarr()

    {

    int[] a={3,8,6,1,2};

    double[] f={3.5,6.8,1.4,67.9};

    Sort s=new Sort();

    s.sort2(a); FloatSort s2=new FloatSort();

    s2.sort2(f);

    }

    publicstatic

    void

    main(String[] args)

    {

    TestSort t=new TestSort();

    t.arr();

    }

    }

  • 7/31/2019 Overriding Refined

    28/43

    Will this work?

    publicclass

    TestSort

    {

    publicvoidarr()

    {

    int[] a={3,8,6,1,2};

    double[] f={3.5,6.8,1.4,67.9};

    Sort s=new Sort();

    s.sort2(a); Sort s2=new FloatSort();

    s2.sort2(f);

    }

    publicstatic

    void

    main(String[] args)

    {

    TestSort t=new TestSort();

    t.arr();

    }

    }

    METHODS THAT ARE BOTH

  • 7/31/2019 Overriding Refined

    29/43

    METHODS THAT ARE BOTH

    OVERLOADED AND

    OVERRIDDEN publicclass Animal

    {

    publicvoideat()

    {

    System.out.println("Generic Animal Eating Generically");

    }

    }

    class Horse extends Animal

    {

    publicvoideat()

    {

    System.out.println("Horse eating hay ");

    }

    publicvoideat(String s) {

    System.out.println("Horse eating " + s);

    }

    }

  • 7/31/2019 Overriding Refined

    30/43

  • 7/31/2019 Overriding Refined

    31/43

  • 7/31/2019 Overriding Refined

    32/43

  • 7/31/2019 Overriding Refined

    33/43

    ANSWER

    Answer: B is correct, an abstract class need not

    implement any or all of an interfacesmethods.

    E is correct, the class implements theinterface method and additionally overloadsthe twiddle() method.

    A is incorrect because abstract methodshave no body.

    C is incorrect because classes implementinterfaces they dont extend them.

    D is incorrect because overloading a methodis not implementing it.

  • 7/31/2019 Overriding Refined

    34/43

    Given:

    class Clidder { private final void flipper() { System.out.println("Clidder"); } } public class Clidlet extends Clidder { public final void flipper() { System.out.println("Clidlet"); } public static void main(String [] args) { new Clidlet().flipper(); } } What is the result? A. Clidlet B. Clidder

    C. Clidder Clidlet D. Clidlet Clidder E. Compilation fails

  • 7/31/2019 Overriding Refined

    35/43

    ANSWER

    A is correct. Although a finalmethod cannot be overridden, in this

    case, the method is private, and

    therefore hidden. The effect is that anew, accessible, method flipper is

    created. The method invoked is simply

    that of the child class, and no erroroccurs.

  • 7/31/2019 Overriding Refined

    36/43

    Given:

    1. class Plant { 2. String getName() { return "plant"; } 3. Plant getType() { return this; } 4. } 5. class Flower extends Plant { 6. // insert code here 7. }

    8. class Tulip extends Flower { }

    Which statement(s), inserted at line 6,will compile? (Choose all that apply.)

  • 7/31/2019 Overriding Refined

    37/43

    A. Flower getType() { return this; } B. String getType() { return "this"; }

    C. Plant getType() { return this; }

    D. Tulip getType() { return new Tulip();

    }

  • 7/31/2019 Overriding Refined

    38/43

    ANSWER

    A, C, and D are correct. A and Dare examples of co-variant returns,

    i.e., Flower and Tulip are both

    subtypes of Plant.

    B is incorrect, String is not asubtype of Plant.

  • 7/31/2019 Overriding Refined

    39/43

    Given

    1. class Programmer { 2. Programmer debug() { return this; }

    3. }

    4. class SCJP extends Programmer { 5. // insert code here

    6. }

    Which, inserted at line 5, will compile?(Choose all that apply.)

  • 7/31/2019 Overriding Refined

    40/43

    A. Programmer debug() { return this; } B. SCJP debug() { return this; }

    C. Object debug() { return this; }

    D. int debug() { return 1; }

    E. int debug(int x) { return 1; }

    F. Object debug(int x) { return this; }

  • 7/31/2019 Overriding Refined

    41/43

    ANSWER

    A, B,E,F are correct.

  • 7/31/2019 Overriding Refined

    42/43

  • 7/31/2019 Overriding Refined

    43/43

    References:

    Head First Java, 2nd Edition,by KathySierra and Bert Bates.

    SCJP Sun Certified Programmer for

    Java 5 Study Guide (Exam 310-055),by Kathy Sierra and Bert Bates.