overriding/overloading srinivas. exam objectives ï¶ given a code example, determine if a...

Download OVERRIDING/OVERLOADING Srinivas. EXAM OBJECTIVES ï¶ Given a code example, determine if a method is correctly overriding or overloading another method,

Post on 12-Jan-2016

219 views

Category:

Documents

1 download

Embed Size (px)

TRANSCRIPT

  • OVERRIDING/OVERLOADINGSrinivas

  • EXAM OBJECTIVESGiven a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method.

    Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass, overridden, or overloaded constructors.

  • OVERRIDINGWhat is overriding?

    The child class provides alternative implementation for parent class method.

    The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type.

    Overridden method: In the superclass.

    Overriding method: In the subclass.

  • METHOD OVERRIDINGExample:public class Car {public void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari extends Car{public void maxSpeed(){System.out.println("Max speed is 120 mph");} public void msc(){}}

  • public class TestCar{public static void main(String args[]){Ferrari f=new Ferrari();f.maxSpeed();}OR

    public static void main(String args[]){Car f=new Ferrari();f.maxSpeed();}}

  • In the preceding code, the test class uses a Car reference to invoke a method on a Ferrari 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 to a Car.

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

    JVM sees the real object at the other end of the reference and invokes the proper method.

  • RULES FOR METHOD OVERRIDINGEXACT argument list matching.

    public class Car {public void maxSpeed(int speed){System.out.println("Max speed is +speed+ mph");}}

    class Ferrari extends Car{public void maxSpeed(float speed){System.out.println("Max speed is +speed+ mph");} public void msc(){}}

  • RULES FOR METHOD OVERRIDINGThe return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass.

    class Alpha {Alpha doStuff(char c) {return new Alpha();}}

    class Beta extends Alpha {Beta doStuff(char c) { return new Beta();// legal override in Java 1.5}}

  • RULES FOR METHOD OVERRIDINGThe access level can't be more restrictive than the overridden method's.

    public class Car {public void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari extends Car{private void maxSpeed(){System.out.println("Max speed is 120 mph");} public void msc(){}}

  • RULES FOR METHOD OVERRIDINGThe access level CAN be less restrictive than that of the overridden method.

    public class Car {protected void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari extends Car{public void maxSpeed(){System.out.println("Max speed is 120 mph");} public void msc(){}}

  • RULES FOR METHOD OVERRIDINGPossible only through inheritance.

    public class Car {protected void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari {public void maxSpeed(){System.out.println("Max speed is 120 mph");} public void msc(){}}

  • RULES FOR METHOD OVERRIDINGThe overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception.An unchecked exception, also called runtime exception, is detected only at runtime. Examples of unchecked exceptions: ArithmeticException ArrayIndexOutOfBoundsException NullPointerException NumberFormatException

  • public class NoRunExc {public void divideBy(){int result= 100/1;System.out.println(result);}

    public static void main(String[] args){NoRunExc n=new NoRunExc();n.divideBy();NoRunExc r=new RunExc();r.divideBy();}}

    class RunExc extends NoRunExc{public void divideBy() throws ArithmeticException{int result= 100/0;System.out.println(result);}}

  • RULES FOR METHOD OVERRIDINGThe overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.A checked exception is an exception that is checked at compile time. The compiler will complain if a checked exception is not handled appropriately.Examples of checked exceptions: IOException FileNotFoundException EOFException

  • RIGHTimport java.io.*;public class Exc {public void openFile() throws IOException{try {FileWriter fw=new FileWriter("Filename.txt");} catch (IOException e) {e.printStackTrace();}

    }}

    class Exc2 extends Exc{public void openFile() throws FileNotFoundException

    {try {FileReader fw=new FileReader("Filename.txt");} catch (FileNotFoundException e) {e.printStackTrace();}

    }}

  • WRONGimport java.io.*;public class Exc {public void openFile() throws FileNotFoundException

    {try {FileWriter fw=new FileWriter("Filename.txt");} catch (IOException e) {e.printStackTrace();}

    }}

    class Exc2 extends Exc{public void openFile() throws IOException

    {try {FileReader fw=new FileReader("Filename.txt");} catch (FileNotFoundException e) {e.printStackTrace();}

    }}

  • 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.

  • import java.io.*;public class Exc {public void openFile() throws IOException{try {FileReader fw=new FileReader("Filename.txt");} catch (FileNotFoundException e) {e.printStackTrace();}

    }}

    class Exc2 extends Exc{public void openFile(){ System.out.println(Ill open the file later"); }}

  • RULES FOR METHOD OVERRIDINGYou cannot override a method marked final.You cannot override a method marked static.

  • What happens here?public class Car {public final void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari extends Car{public void maxSpeed(){System.out.println("Max speed is 120 mph");} public void msc(){}}

  • Invoking a Superclass Version of an Overridden MethodUse the code in the overridden method.Also add extra features in overriding method.

  • public class Car {protected void maxSpeed(){System.out.println("Max speed is 60 mph");}}

    class Ferrari extends Car{public void maxSpeed(){super.maxSpeed();System.out.println("I can race");}

    }

  • Introduction to overloadingSame name, different arguments.Code deals with different argument types rather than forcing the caller to do conversions prior to invoking your method.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.

  • In same classpublic class Sort {public void sort2(int[] a ){//Program to sort integers}

    public void sort2(String[] a ){ //Program to sort Strings}

  • public class TestSort {public void arr(){int[] a={3,8,6,1,2};String[] s={"Sachin","Sourav","Dravid"};Sort s=new Sort();s.sort2(a);s.sort2(s);}

    public static void main(String[] args){TestSort t=new TestSort();t.arr();}}

  • In different classespublic class Sort {public void sort2(int[] a ){//Program to sort integers}}class FloatSort extends Sort{public void sort2(double[] a ){ //Program to sort floats}

  • public class TestSort {public void arr(){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);}

    public static void main(String[] args){TestSort t=new TestSort();t.arr();}}

  • Will this work?public class TestSort {public void arr(){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);}

    public static void main(String[] args){TestSort t=new TestSort();t.arr();}}

  • METHODS THAT ARE BOTH OVERLOADED AND OVERRIDDENpublic class Animal {public void eat() {System.out.println("Generic Animal Eating Generically");}}

    class Horse extends Animal {public void eat() {System.out.println("Horse eating hay ");}public void eat(String s) {System.out.println("Horse eating " + s);}}

  • Given: public abstract interface Frobnicate { public void twiddle(String s); }

    Which is a correct class? (Choose all that apply.)

    A. public abstract class Frob implements Frobnicate {public abstract void twiddle(String s) { }}

    B. public abstract class Frob implements Frobnicate { }

    C. public class Frob extends Frobnicate {public void twiddle(Integer i) { }}

    D. public class Frob implements Frobnicate {public void twiddle(Integer i) { }}

    E. public class Frob implements Frobnicate {public void twiddle(String i) { }public void twiddle(Integer s) { }}

  • ANSWERAnswer: B is correct, an abstract class need not implement any or all of an interfaces methods.E is correct, the class implements the interface method and additionally overloads the twiddle() method. A is incorrect because abstract methods have no body.C is incorrect because classes implement interfaces they dont extend them.D is incorrect because overloading a method is not implementing it.

  • 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. ClidletB. ClidderC. Clidder ClidletD. Clidlet ClidderE. Compilation fails

  • ANSWER A is correct. Although a final method cannot be overridden, in this case, the method is private, and therefore hidden. The effect is that a new, accessible, method flipper is created. The method invoked is simply that of the child class, and no error occurs.

  • Given:1. class Plant {2. String getName(

View more >