What is function overloading and overriding in java

what is method overloading and method overriding in java with example, what is difference between overloading and overriding in java example pdf free download
OliviaCutts Profile Pic
OliviaCutts,France,Teacher
Published Date:01-08-2017
Your Website URL(Optional)
Comment
Color profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Blind Folio 5:1 5 Object Orientation, Overloading and Overriding, Constructors, and Return Types CERTIFICATION OBJECTIVES • Benefits of Encapsulation  Overridden and Overloaded Methods  Constructors and Instantiation  Legal Return Types ✓ Two-Minute Drill Q&A Self Test P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:10 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 2 he objectives in this section revolve (mostly) around object-oriented (OO) programming including encapsulation, inheritance, and polymorphism. For the exam, you need to Tknow whether a code fragment is correctly or incorrectly implementing some of the key OO features supported in Java. You also need to recognize the difference between overloaded and overridden methods, and be able to spot correct and incorrect implementations of both. Because this book focuses on your passing the programmer’s exam, only the critical exam-specific aspects of OO software will be covered here. If you’re not already well versed in OO concepts, you could (and should) study a dozen books on the subject of OO development to get a broader and deeper understanding of both the benefits and the techniques for analysis, design, and implementation. But for passing the exam, the relevant concepts and rules you need to know are covered here. (That’s a disclaimer, because we can’t say you’ll be a “complete OO being” by reading this chapter.) (We can say, however, that your golf swing will improve.) We think you’ll find this chapter a nice treat after slogging your way through the technical (and picky) details of the previous chapters. Object-oriented programming is a festive topic, so may we suggest you don the appropriate clothing—say, a Hawaiian shirt and a party hat. Grab a margarita (if you’re new to OO, maybe nonalcoholic is best) and let’s have some fun (OK so maybe we exaggerated a little about the whole party aspect. Still, you’ll find this section both smaller and less detailed than the previous four.) (And this time we really mean it.) CERTIFICATION OBJECTIVE Benefits of Encapsulation (Exam Objective 6.1) State the benefits of encapsulation in object-oriented design and write code that implements tightly encapsulated classes and the relationships IS-A and HAS-A. Imagine you wrote the code for a class, and another dozen programmers from your company all wrote programs that used your class. Now imagine that you didn’t like the way the class behaved, because some of its instance variables were being set (by P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:11 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 5 Composite Default screen Benefits of Encapsulation (Exam Objective 6.1) 3 the other programmers from within their code) to values you hadn’t anticipated. Their code brought out errors in your code. (Relax, this is just hypothetical…) Well, it is a Java program, so you should be able just to ship out a newer version of the class, which they could replace in their programs without changing any of their own code. This scenario highlights two of the promises/benefits of OO: flexibility and maintainability. But those benefits don’t come automatically. You have to do something. You have to write your classes and code in a way that supports flexibility and maintainability. So what if Java supports OO? It can’t design your code for you. For example, imagine if you (not the real you, but the hypothetical-not-as-good-a-programmer you) made your class withpublic instance variables, and those other programmers were setting the instance variables directly, as the following code demonstrates: public class BadOO public int size; public int weight; … public class ExploitBadOO public static void main (String args) BadOO b = new BadOO(); b.size = -5; // Legal but bad And now you’re in trouble. How are you going to change the class in a way that lets you handle the issues that come up when somebody changes the size variable to a value that causes problems? Your only choice is to go back in and write method code for adjusting size (asetSize(int a) method, for example), and then protect the size variable with, say, aprivate access modifier. But as soon as you make that change to your code, you break everyone else’s The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation. You want to hide implementation details behind apublic programming interface. By interface, we mean the set of accessible methods your code makes available for other code to call—in other words, your code’s API. By hiding implementation details, you can rework your method code (perhaps also altering the way variables are used by your class) without forcing a change in the code that calls your changed method. P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:11 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 4 If you want maintainability, flexibility, and extensibility (and of course, you do), your design must include encapsulation. How do you do that? ■ Keep your instance variables protected (with an access modifier, often private). ■ Make public accessor methods, and force calling code to use those methods. ■ For the methods, use the JavaBeans naming convention of setsomeProperty and getsomeProperty. Figure 5-1 illustrates the idea that encapsulation forces callers of our code to go through methods rather than accessing variables directly. We call the access methods getters and setters although some prefer the fancier terms (more impressive at dinner parties) accessors and mutators. Personally, we don’t FIGURE 5-1 The nature of encapsulation P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:11 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Benefits of Encapsulation (Exam Objective 6.1) 5 like the word mutate. Regardless of what you call them, they’re methods that others must go through in order to access your instance variables. They look simple, and you’ve probably been using them forever: public class Box // protect the instance variable; only an instance // of Box can access it private int size; // Provide public getters and setters public int getSize() return size; public void setSize(int newSize) size = newSize; Wait a minute…how useful is the previous code? It doesn’t even do any validation or processing. What benefit can there be from having getters and setters that add no additional functionality? The point is, you can change your mind later, and add more code to your methods without breaking your API. Even if you don’t think you really need validation or processing of the data, good OO design dictates that you plan for the future. To be safe, force calling code to go through your methods rather than going directly to instance variables. Always. Then you’re free to rework your method implementations later, without risking the wrath of those dozen programmers who know where you live. And have been doing Tae-bo. And drink way too much Mountain Dew. Look out for code that appears to be asking about the behavior of a method, when the problem is actually a lack of encapsulation. Look at the following example, and see if you can figure out what’s going on: class Foo public int left = 9; public int right = 3; public void setLeft(int leftNum) left = leftNum; right = leftNum/3; // lots of complex test code here P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:11 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 6 Now consider this question: Is the value of right always going to be one-third the value of left? It looks like it will, until you realize that users of the Foo class don’t need to use the setLeft() method They can simply go straight to the instance variables and change them to any arbitrary int value. IS-A and HAS-A Relationships For the exam you need to be able to look at code and determine whether the code demonstrates an IS-A or HAS-A relationship. The rules are simple, so this should be one of the few areas where answering the questions correctly is almost a no-brainer. (Well, at least it would have been a no-brainer if we (exam creators) hadn’t tried our best to obfuscate the real problem.) (If you don’t know the word “obfuscate”, stop and look it up, then write and tell us what it means.) IS-A In OO, the concept of IS-A is based on inheritance. IS-A is a way of saying, “this thing is a type of that thing.” For example, a Mustang is a type of horse, so in OO terms we can say, “Mustang IS-A Horse.” Subaru IS-A Car. Broccoli IS-A Vegetable (not a very fun one, but it still counts). You express the IS-A relationship in Java through the keywordextends: public class Car // Cool Car code goes here public class Subaru extends Car // Important Subaru-specific stuff goes here // Don't forget Subaru inherits accessible Car members A Car is a type of Vehicle, so the inheritance tree might start from the Vehicle class as follows: public class Vehicle … public class Car extends Vehicle … public class Subaru extends Car … In OO terms, you can say the following: ■ Vehicle is the superclass of Car. ■ Car is the subclass of Vehicle. P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:12 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Benefits of Encapsulation (Exam Objective 6.1) 7 ■ Car is the superclass of Subaru. ■ Subaru is the subclass of Vehicle. ■ Car inherits from Vehicle. ■ Subaru inherits from Car. ■ Subaru inherits from Vehicle. ■ Subaru is derived from Car. ■ Car is derived from Vehicle. ■ Subaru is derived from Vehicle. ■ Subaru is a subtype of Car. ■ Subaru is a subtype of Vehicle. Returning to our IS-A relationship, the following statements are true: “Car extends Vehicle” means “Car IS-A Vehicle.” “Subaru extends Car” means “Subaru IS-A Car.” And we can also say: “Subaru IS-A Vehicle” because a class is said to be “a type of” anything further up in its inheritance tree. If Fooinstanceof Bar, then class Foo IS-A Bar, even if Foo doesn’t directly extend Bar, but instead extends some other class that is a subclass of Bar. Figure 5-2 illustrates the inheritance tree for Vehicle, Car, and Subaru. The arrows move from the subclass to the superclass. In other words, a class’ arrow points toward the class it extends from. FIGURE 5-2 Inheritance tree for Vehicle, Car, and Subaru P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:12 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 8 HAS-A HAS-A relationships are based on usage, rather than inheritance. In other words, class A HAS-A B if code in class A has a reference to an instance of class B. For example, you can say the following, A Horse IS-A Animal. A Horse HAS-A Halter. and the code looks like this: public class Animal public class Horse extends Animal private Halter myHalter; In the preceding code, the Horse class has an instance variable of type Halter, so you can say that “Horse HAS-A Halter.” In other words, Horse has a reference to a Halter. Horse code can use that Halter reference to invoke methods on the Halter, and get Halter behavior without having Halter-related code (methods) in the Horse class itself. Figure 5-3 illustrates the HAS-A relationship between Horse and Halter. HAS-A relationships allow you to design classes that follow good OO practices by not having monolithic classes that do a gazillion different things. Classes (and thus the objects instantiated from those classes) should be specialists. The more specialized the class, the more likely it is that you can reuse the class in other applications. If you put all the Halter-related code directly into the Horse class, you’ll end up duplicating code in the Cow class, Sheep class, UnpaidIntern class, and any other class that might need Halter behavior. By keeping the Halter code in a separate, specialized Halter class, you have the chance to reuse the Halter class in multiple applications. FIGURE 5-3 HAS-A relationship between Horse and Halter P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:12 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Benefits of Encapsulation (Exam Objective 6.1) 9 Users of the Horse class (that is, code that calls methods on a Horse instance), think that the Horse class has Halter behavior. The Horse class might have a tie(LeadRope rope) method, for example. Users of the Horse class should never have to know that when they invoke thetie() method, the Horse object turns around and delegates the call to its Halter class by invokingmyHalter.tie(rope). The scenario just described might look like this: public class Horse extends Animal private Halter myHalter; public void tie(LeadRope rope) myHalter.tie(rope); // Delegate tie behavior to the // Halter object public class Halter public void tie(LeadRope aRope) // Do the actual tie work here In OO, we don’t want callers to worry about which class or which object is actually doing the real work. To make that happen, the Horse class hides implementation details from Horse users. Horse users ask the Horse object to do things (in this case, tie itself up), and the Horse will either do it or, as in this example, ask something else to do it. To the caller, though, it always appears that the Horse object takes care of itself. Users of a Horse should not even need to know that there is such a thing as a Halter class. Now that we’ve looked at some of the OO characteristics, here are some possible scenario questions and their solutions. SCENARIO & SOLUTION What benefits do you gain from encapsulation? Ease of code maintenance, extensibility, and code clarity. What is the object-oriented relationship between An IS-A relationship: Oak IS-A Tree. a tree and an oak? What is the object-oriented relationship between A HAS-A relationship: City HAS-A Road. a city and a road? P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:12 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 10 FROM THE CLASSROOM Object-Oriented Design IS-A and HAS-A relationships and allow designers to design and easily modify encapsulation are just the tip of the iceberg classes without having to write code first, when it comes to object-oriented design. because object-oriented components are Many books and graduate theses have been represented graphically. This allows the designer dedicated to this topic. The reason for the to create a map of the class relationships and emphasis on proper design is simple: money. helps them recognize errors before coding The cost to deliver a software application has begins. Another recent innovation in object- been estimated to be as much as 10 times oriented design is design patterns. Designers more expensive for poorly designed programs. noticed that many object-oriented designs Having seen the ramifications of poor designs, apply consistently from project to project, and I can assure you that this estimate is not that it was useful to apply the same designs far-fetched. because it reduced the potential to introduce Even the best object-oriented designers new design errors. Object-oriented designers make mistakes. It is difficult to visualize the then started to share these designs with each relationships between hundreds, or even other. Now, there are many catalogs of these thousands, of classes. When mistakes are design patterns both on the Internet and in discovered during the implementation (code book form. writing) phase of a project, the amount of Although passing the Java certification code that has to be rewritten can sometimes exam does not require you to understand cause programming teams to start over object-oriented design this thoroughly, from scratch. hopefully this background information will The software industry has evolved to aid help you better appreciate why the test writers the designer. Visual object modeling languages, chose to include encapsulation and is a and such as the Unified Modeling Language (UML), has a relationships on the exam. —Jonathan Meeks, Sun Certified Java Programmer P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 5 Composite Default screen Overridden and Overloaded Methods (Exam Objective 6.2) 11 CERTIFICATION OBJECTIVE Overridden and Overloaded Methods (Exam Objective 6.2) Write code to invoke overridden or overloaded methods and parental or overloaded constructors, and describe the effect of invoking these methods. Methods can be overloaded or overridden, but constructors can be only overloaded. Overloaded methods and constructors let you use the same method name (or constructor) but with different argument lists. Overriding lets you redefine a method in a subclass, when you need new subclass-specific behavior. Overridden Methods Anytime you have a class that inherits a method from a superclass, you have the opportunity to override the method (unless, as you learned earlier, the method is markedfinal). The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. The following example demonstrates a Horse subclass of Animal overriding the Animal version of theeat() method: 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, oats, and horse treats"); For abstract methods you inherit from a superclass, you have no choice. You must implement the method in the subclass unless the subclass is also abstract. Abstract methods are said to be implemented by the concrete subclass, but this is virtually the same as saying that the concrete subclass overrides the abstract methods of the superclass. So you should think of abstract methods as methods you’re forced to override. The Animal class creator might have decided that for the purposes of polymorphism, all Animal subtypes should have aneat() method defined in a unique, specific way. Polymorphically, when someone has an Animal reference that refers not to an P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 12 Animal instance, but to an Animal subclass instance, the caller should be able to invokeeat() on the Animal reference, but the actual runtime object (say, a Horse instance) will run its own specificeat() method. Marking theeat() method abstract is the Animal programmer’s way of saying to all subclass developers, “It doesn’t make any sense for your new subtype to use a genericeat() method, so you have to come up with your owneat() method implementation” An example of using polymorphism looks like this: public class TestAnimals public static void main (String args) Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() 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, oats, and horse treats"); public void buck() In the preceding code, the test class uses an Animal reference to invoke a method on a Horse object. Remember, the compiler will allow only methods in class Animal to be invoked when using a reference to an Animal. The following would not be legal given the preceding code: Animal c = new Horse(); c.buck(); // Can't invoke buck(); // Animal class doesn't have that method The compiler looks only at the reference type, not the instance type. Polymorphism lets you use a more abstract supertype (including an interface) reference to refer to one of its subtypes (including interface implementers). The overriding method cannot have a more restrictive access modifier than the method being overridden (for example, you can’t override a method markedpublic and make itprotected). Think about it: if the Animal class advertises a publiceat() P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Overridden and Overloaded Methods (Exam Objective 6.2) 13 method and someone has an Animal reference (in other words, a reference declared as type Animal), that someone will assume it’s safe to calleat() on the Animal reference regardless of the actual instance that the Animal reference is referring to. If a subclass were allowed to sneak in and change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true object’s (Horse) version of the method rather than the reference type’s (Animal) version—the program would die a horrible death. (Not to mention the emotional distress for the one who was betrayed by the rogue subclass.) Let’s modify the polymorphic example we saw earlier: public class TestAnimals public static void main (String args) Animal a = new Animal(); Animal b = new Horse(); //Animal ref, but a Horse object a.eat(); // Runs the Animal version of eat() b.eat(); // Runs the Horse version of eat() class Animal public void eat() System.out.println("Generic Animal Eating Generically"); class Horse extends Animal private void eat() System.out.println("Horse eating hay, oats, and horse treats"); If this code were allowed to compile (which it’s not, by the way—the compiler wants you to know that it didn’t just fall off the turnip truck), the following would fail at runtime: Animal b = new Horse(); // Animal ref, but a Horse // object , so far so good b.eat(); // Meltdown The variable b is of type Animal, which has apublic eat() method. But remember that at runtime, Java uses virtual method invocation to dynamically select the actual version of the method that will run, based on the actual instance. An Animal reference can always refer to a Horse instance, because Horse IS-A(n) Animal. What P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 14 makes that superclass reference to a subclass instance possible is that the subclass is guaranteed to be able to do everything the superclass can do. Whether the Horse instance overrides the inherited methods of Animal or simply inherits them, anyone with an Animal reference to a Horse instance is free to call all accessible Animal methods. For that reason, an overriding method must fulfill the contract of the superclass. The rules for overriding a method are as follows: ■ The argument list must exactly match that of the overridden method. ■ The return type must exactly match that of the overridden method. ■ The access level must not be more restrictive than that of the overridden method. ■ The access level can be less restrictive than that of the overridden method. ■ The overriding method must not throw new or broader checked exceptions than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it’s a subclass of FileNotFoundException. ■ The overriding method can throw narrower or fewer exceptions. Just because an overridden method “takes risks” doesn’t mean that the overriding subclass’ exception takes the same risks. Bottom line: An overriding method doesn’t have to declare any exceptions that it will never throw, regardless of what the overridden method declares. ■ You cannot override a method markedfinal. ■ If a method can’t be inherited, you cannot override it. For example, the following code is not legal: public class TestAnimals public static void main (String args) Horse h = new Horse(); h.eat(); // Not legal because Horse didn't inherit eat() class Animal private void eat() System.out.println("Generic Animal Eating Generically"); class Horse extends Animal P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Overridden and Overloaded Methods (Exam Objective 6.2) 15 Invoking a Superclass Version of an Overridden Method Often, you’ll want to take advantage of some of the code in the superclass version of a method, yet still override it to provide some additional specific behavior. It’s like saying, “Run the superclass version of the method, then come back down here and finish with my subclass additional method code.” (Note that there’s no requirement that the superclass version run before the subclass code.) It’s easy to do in code using the keywordsuper as follows: public class Animal public void eat() public void printYourself() // Useful printing code goes here class Horse extends Animal public void printYourself() // Take advantage of Animal code, then add some more super.printYourself(); // Invoke the superclass // (Animal) code // Then come back and do // additional Horse-specific // print work here Examples of Legal and Illegal Method Overrides Let’s take a look at overriding theeat() method of Animal: public class Animal public void eat() Table 5-1 lists examples of illegal overrides of the Animaleat() method, given the preceding version of the Animal class. Overloaded Methods Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). Overloading a method often means you’re being a little nicer to those who call your methods, because your code P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:13 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 16 TABLE 5-1 Examples of Illegal Overrides Illegal Override Code Problem with the Code private void eat() Access modifier is more restrictive public void eat() throws Declares a checked exception not declared by IOException superclass version public void eat(String food) A legal overload, not an override, because the argument list changed public String eat() Not an override because of the return type, but not an overload either because there’s no change in the argument list takes on the burden of coping with different argument types rather than forcing the caller to do conversions prior to invoking your method. The rules are simple: ■ Overloaded methods must change the argument list. ■ Overloaded methods can change the return type. ■ Overloaded methods can change the access modifier. ■ Overloaded methods can declare new or broader checked exceptions. ■ A method can be overloaded in the same class or in a subclass. Legal Overloads Let’s look at a method we want to overload: public void changeSize(int size, String name, float pattern) The following methods are legal overloads of thechangeSize() method: public void changeSize(int size, String name) public int changeSize(int size, float pattern) public void changeSize(float pattern, String name) throws IOException Be careful to recognize when a method is overloaded rather than overridden. You might see a method that appears to be violating a rule for overriding, but which is actually a legal overload, as follows: P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:14 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Overridden and Overloaded Methods (Exam Objective 6.2) 17 public class Foo public void doStuff(int y, String s) public void moreThings(int x) class Bar extends Foo public void doStuff(int y, float s) throws IOException You might be tempted to see the IOException as the problem, seeing that the overridden doStuff() method doesn’t declare an exception, and knowing that IOException is checked by the compiler. But the doStuff() method is not overridden at all Subclass Bar overloads the doStuff() method, by varying the argument list, so the IOException is fine. Invoking Overloaded Methods When a method is invoked, more than one method of the same name might exist for the object type you’re invoking a method on. For example, the Horse class might have three methods with the same name but with different argument lists, which means the method is overloaded. Deciding which of the matching methods to invoke is based on the arguments. If you invoke the method with a String argument, the overloaded version that takes a String is called. If you invoke a method of the same name but pass it a float, the overloaded version that takes a float will run. If you invoke the method of the same name but pass it a Foo object, and there isn’t an overloaded version that takes a Foo, then the compiler will complain that it can’t find a match. The following are examples of invoking overloaded methods: class Adder public int addThem(int x, int y) return x + y; // Overload the addThem method to add doubles instead of ints public double addThem(double x, double y) return x + y; // From another class, invoke the addThem() method public class TestAdder public static void main (String args) P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:14 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 18 Adder add = new Adder(); int b = 27; int c = 3; int result = a.addThem(b,c); // Which addThem is invoked? double doubleResult = a.addThem(22.5,89.36); // Which addThem? In the preceding TestAdder code, the first call toa.addThem(b,c) passes two ints to the method, so the first version ofaddThem()—the overloaded version that takes two int arguments—is called. The second call toa.addThem(22.5, 89.36) passes two doubles to the method, so the second version ofaddThem()—the overloaded version that takes two double arguments—is called. Invoking overloaded methods that take object references rather than primitives is a little more interesting. Say you have an overloaded method such that one version takes an Animal and one takes a Horse (subclass of Animal). If you pass a Horse object in the method invocation, you’ll invoke the overloaded version that takes a Horse. Or so it looks at first glance: class Animal class Horse extends Animal class UseAnimals public void doStuff(Animal a) System.out.println("In the Animal version"); public void doStuff(Horse h) System.out.println("In the Horse version"); public static void main (String args) UseAnimals ua = new UseAnimals(); Animal animalObj = new Animal(); Horse horseObj = new Horse(); ua.doStuff(animalObj); ua.doStuff(horseObj); The output is what you expect: P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:14 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Overridden and Overloaded Methods (Exam Objective 6.2) 19 in the Animal version in the Horse version But what if you use an Animal reference to a Horse object? Animal animalRefToHorse = new Horse(); ua.doStuff(animalRefToHorse); Which of the overloaded versions is invoked? You might want to say, “The one that takes a Horse, since it’s a Horse object at runtime that’s being passed to the method.” But that’s not how it works. The preceding code would actually print in the Animal version Even though the actual object at runtime is a Horse and not an Animal, the choice of which overloaded method to call is not dynamically decided at runtime. Just remember, the reference type (not the object type) determines which overloaded method is invoked To summarize, which overridden method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type passed at compile time. Polymorphism in Overloaded and Overridden Methods How does polymorphism work with overloaded methods? From what we just looked at, it doesn’t appear that polymorphism matters when a method is overloaded. If you pass an Animal reference, the overloaded method that takes an Animal will be invoked, even if the actual object passed is a Horse. Once the Horse masquerading as Animal gets in to the method, however, the Horse object is still a Horse despite being passed into a method expecting an Animal. So it’s true that polymorphism doesn’t determine which overloaded version is called; polymorphism does come into play when the decision is about which overridden version of a method is called. But sometimes, a method is both overloaded and overridden. Imagine the Animal and Horse classes look like this: public class Animal public void eat() System.out.println("Generic Animal Eating Generically"); P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:14 PMColor profile: Generic CMYK printer profile CertPrs8(SUN) / Sun Certified Programmer & Developer for Java 2 Study Guide / Sierra / 222684-6 / Chapter 5 Composite Default screen Chapter 5: Object Orientation, Overloading and Overriding, Constructors, and Return Types 20 public class Horse extends Animal public void eat() System.out.println("Horse eating hay "); public void eat(String s) System.out.println("Horse eating " + s); Notice that the Horse class has both overloaded and overridden theeat() method. Table 5-2 shows which version of the threeeat() methods will run depending on how they are invoked. TABLE 5-2 Overloaded and Overridden Method Invocations Method Invocation Code Result Animal a = new Animal(); Generic Animal Eating Generically a.eat(); Horse h = new Horse(); Horse eating hay h.eat(); Animal ah = new Horse(); Horse eating hay ah.eat(); Polymorphism works—the actual object type (Horse), not the reference type (Animal), is used to determine whicheat() is called. Horse he = new Horse(); Horse eating Apples he.eat("Apples"); The overloadedeat(String s) method is invoked. Animal a2 = new Animal(); Compiler error Compiler sees that Animal class doesn’t have an a2.eat("treats"); eat() method that takes a String. Animal ah2 = new Horse(); Compiler error Compiler still looks only at the reference type, ah2.eat("Carrots"); and sees that Animal doesn’t have aneat() method that takes a string. Compiler doesn’t care that the actual object might be a Horse at runtime. P:\010Comp\CertPrs8\684-6\ch05.vp Wednesday, November 13, 2002 5:17:14 PM

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.