Saturday, January 8, 2011

Chapter 10: Implementing an Interface

We have been using references to the term “Implementing an Interface” throughout the preceding chapters and we havent yet actually dug deep into this topic. As you might remember, an Interface is nothing but a contract as to how a class should behave. It just declares the behavior as empty methods and the implementing class actually writes the code that will determine the behavior.

When you implement an interface, you’re agreeing to adhere to the contract defined in the interface. That means you’re agreeing to provide legal implementations for every method defined in the interface, and that anyone who knows what the interface methods look like can rest assured that they can invoke those methods on an instance of your implementing class. (Thy need not bother much about how you have implemented it. All they bother about is whether a method of the name mentioned in the interface is available or not)

Now, you might stop me and ask, what if I implement an interface and opt not to write code for a method that I am supposed to? The answer is simple. The compiler wouldn't let you do that. You cannot successfully implement an interface without providing method implementation for all the methods declared inside the interface. This is how the java system ensures that when someone knows a certain method name in an interface and has an instance of a class that implements it, can actually call that method without fear that the method isnt implemented inside the class.
Assuming an interface, Convertible, with two methods: openHood(), and setOpenHoodFactor(), the following class will compile:

public class Ball implements Convertible { // Keyword 'implements'
public void openHood() { }
public void setOpenHoodFactor(int bf) { }
}

Ok, I know what you are thinking now. “This has got to be the worst implementation class that you have seen”. Though it compiles and runs as well, it is actually doing nothing… the interface contract guarantees that the class implementing it will have a method of a particular name but it never guaranteed a good implementation. In other words, the compiler does not bother whether you have code inside your method or not. All it cares is if you have methods of the matching names as in the interface. That's all…

Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. In order to be a legal implementation class, a nonabstract implementation class must do the following:
• Provide concrete (nonabstract) implementations for all methods from the declared interface.
• Follow all the rules for legal overrides.
• Declare no checked exceptions on implementation methods other than those declared by the interface method, or subclasses of those declared by the interface method.
• Maintain the signature of the interface method, and maintain the same return type (or a subtype).
• It does not have to declare the exceptions declared in the interface method declaration.

Tip: What if an implementing class does not want to provide implementation for all methods? Can we make that class compile? Of course yes, just make the class abstract. This means that the compiler wont check if all the methods are implemented.
Ex:
abstract class SuperCar implements Convertible { }

Notice anything missing? We never provided the implementation methods. And that’s OK. If the implementation class is abstract, it can simply pass the buck to its first concrete subclass.
You can have a class like:
Public class SuperSuperCar extends SuperCar {
public void openHood() {
System.out.println(“Opening the Hood”);
}
public void setOpenHoodFactor(int bf) {
System.out.println(“Opening the hood at speed: “ + bf);
}
}
This class SuperSuperCar is the first concrete (or non-abstract) class that extends the SuperCar class and actually provides the implementation for the methods in the interface Convertible that the SuperCar class implements.

Exam Tip: You may have questions wherein a class implements an interface but does not provide all the method implementations (check for method signatures too) Unless the implementing class is abstract, the implementing class must provide implementations for all the methods defined in the interface. You should be careful to spot such instances and answer them appropriately.

There are two more rules you need to know before we can wrap up this chapter:
1. A class can implement more than one interface. It’s perfectly legal to say, for example, the following:
public class Car implements Convertible, Serializable, Runnable
{ ... }

You can extend only one class, but implement many interfaces. But remember that subclassing defines who and what you are, whereas implementing defines a role you can play or a hat you can wear, despite how different you might be from some other class implementing the same interface (but from a different inheritance tree).

2. An interface can itself extend another interface, but never implement anything. The following code is perfectly legal:

public interface Convertible extends Moveable { } // ok!

What does that mean? The first concrete (nonabstract) implementation class of Convertible must implement all the methods of Convertible, plus all the methods of Moveable! The subinterface, as we call it, simply adds more requirements to the contract of the superinterface. You’ll see this concept applied in many areas of Java, especially J2EE where you’ll often have to build your own interface that extends one of the J2EE interfaces.

i.e., public class A extends B, C {…} is illegal whereas
public Interface A extends B, C {…} is perfectly legal

Exam Tip: Watch out for legal/illegal usage of extends and implements. There might be quite a few questions on this.
1. class Car {} - No Problems
2. class Ferrari Implements Car {} – Not Ok. Car is a class not an Interface
3. interface Convertible {} – No problems
4. interface Moveable {} – No problems
5. interface CarTop implements Convertible {} – Not Ok. An Interface cannot implement another interface
6. interface CarTop implements Car {} – Not Ok. An Interface cannot implement a class
7. interface CarTop extends Car {} – Not Ok. An Interface cannot extend a class
8. interface CarTop extends Convertible {} - No Problems. An Interface can extend another Interface
9. class Ferrari extends Car, Automobile – Not Ok. A Class cannot extend multiple classes
10. class Ferrari implements Convertible, Moveable {} – No Problems. A Class can implement multiple interfaces
11. class Ferrari extends Car implements Convertible {} – No Problems. A Class can both extend a class and implement an interface
12. class Ferrari implements Convertible extends Car {} - Not Ok. The extends should come first.

Burn these in, and watch for incorrect usage in the questions you get on the exam. Regardless of what the question appears to be testing, the real problem might be the class or interface declaration. Before you get caught up in, lets say, tracing a complex threading flow, check to see if the code will even compile first. (You’ll be really impressed by the effort the exam developers put into distracting you from the real problem.) You take the bait, you choose a wrong answer that would look perfectly legitimate while the code won’t compile in the first place.

Previous Chapter: Chapter 9: Reference Variable Casting

Next Chapter: Chapter 11 - Legal Return Types

1 comment:

  1. Thanks for your comment on my post 10 points on interface in Java. I see you have also covered it quite well. keep the good work going.I also like your finance blog, good one.

    Javin

    ReplyDelete

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers