OVERRIDING/OVERLOADING Srinivas. EXAM OBJECTIVES Given a code example, determine if a method is...

Post on 12-Jan-2016

247 views 1 download

Transcript of OVERRIDING/OVERLOADING Srinivas. EXAM OBJECTIVES Given a code example, determine if a method is...

OVERRIDING/OVERRIDING/OVERLOADINGOVERLOADING

Srinivas

EXAM OBJECTIVESEXAM 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.

OVERRIDINGOVERRIDING What 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 OVERRIDINGMETHOD OVERRIDING Example: 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(){} }

publicpublic classclass TestCar 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 RULES FOR METHOD OVERRIDINGOVERRIDING EXACT 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 RULES FOR METHOD OVERRIDINGOVERRIDING The 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 RULES FOR METHOD OVERRIDINGOVERRIDING The 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 RULES FOR METHOD OVERRIDINGOVERRIDING The 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 RULES FOR METHOD OVERRIDINGOVERRIDING Possible 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 RULES FOR METHOD OVERRIDINGOVERRIDINGThe 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: o ArithmeticException o ArrayIndexOutOfBoundsException o NullPointerException o 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 RULES FOR METHOD OVERRIDINGOVERRIDINGThe 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

RIGHTRIGHT import 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(); }

} }

WRONGWRONG import 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 RULES FOR METHOD OVERRIDINGOVERRIDINGAn 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(“I’ll open the file later"); } }

RULES FOR METHOD RULES FOR METHOD OVERRIDINGOVERRIDINGYou cannot override a method

marked final.You cannot override a method

marked static.

What happens here?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 Invoking a Superclass Version of an Overridden Version of an Overridden MethodMethodUse 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 Introduction to overloadingoverloadingSame 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 classIn 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 classesIn different classes public 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?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 METHODS THAT ARE BOTH OVERLOADED AND OVERLOADED AND OVERRIDDENOVERRIDDEN public 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: Given: public abstract interface public abstract interface Frobnicate { public void Frobnicate { public void twiddle(String s); }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) { } }

ANSWERANSWERAnswer: B is correct, an abstract class need not

implement any or all of an interface’s 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 don’t extend them.

D is incorrect because overloading a method is not implementing it.

Given: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

ANSWERANSWER 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:Given:1. class Plant {2. String getName() { return "plant"; }3. Plant getType() { return this; }4. }5. class Flower extends Plant {6. // insert code here7. }8. class Tulip extends Flower { }

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

A. Flower getType() { return this; }

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

C. Plant getType() { return this; }D. Tulip getType() { return new

Tulip(); }

ANSWERANSWER A, C, and D are correct. A

and D are examples of co-variant returns, i.e., Flower and Tulip are both subtypes of Plant.

B is incorrect, String is not a subtype of Plant.

GivenGiven1. class Programmer {2. Programmer debug() { return

this; }3. }4. class SCJP extends Programmer {5. // insert code here6. }

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

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; }

ANSWERANSWERA, B,E,F are correct.

References:References:

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

SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055),by Kathy Sierra and Bert Bates.