Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

7. Inheritance and Polymorphism: Better ... > Keeping the contract: rules for over...

Keeping the contract: rules for overriding

When you override a method from a superclass, you’re agreeing to fulfill the contract. The contract that says, for example, “I take no arguments and I return a boolean.” In other words, the arguments and return types of your overriding method must look to the outside world exactly like the overridden method in the superclass.

The methods are the contract.

If polymorphism is going to work, the Toaster’s version of the overridden method from Appliance has to work at runtime. Remember, the compiler looks at the reference type to decide whether you can call a particular method on that reference. With an Appliance reference to a Toaster, the compiler cares only if class Appliance has the method you’re invoking on an Appliance reference. But at runtime, the JVM looks not at the reference type (Appliance) but at the actual Toaster object on the heap. So if the compiler has already approved the method call, the only way it can work is if the overriding method has the same arguments and return types. Otherwise, someone with an Appliance reference will call turnOn() as a noarg method, even though there’s a version in Toaster that takes an int. Which one is called at runtime? The one in Appliance. In other words, the turnOn(int level) method in Toaster is not an override!


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint