This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: COMP 250 Winter 2010 32 - interfaces April 7, 2010 Earlier when we discussed Java classes and their inheritance relationships, we pictured a hier- archy where each class (except Object ) extends some other unique class (see inheritance diagram below on the left). Thus Java classes define a tree, with each note having a reference to its parent 1 (superclass). How, if at all, do Java interfaces fit into the class hierarchy? implements implements extends implements extends extends Classes Interfaces As shown above right, an interface is another node in the inheritance diagram. We used dashed arrows to indicate inheritance relationships that involve interfaces. • If a class C implements an interface I then we put a dashed arrow from C to I . (Recall that a “class implements an interface” means that the class provides the method body for each method (signature) defined in the interface.) • One interface (say I2 ) can extend another interface (say I1 ). This means that I2 inherits all the method signatures from I1 . We don’t need to write the method signatures out again in the definition of I2 . In the class hierarchy, we would put a dashed line from I2 to I1 . • Although each class (other than Object ) directly extends exactly one other class, 2 a class C can implement multiple interfaces. The parent interfaces can even contain the same method signature. This is no problem since the interfaces only contain the signatures (not the bodies), so there can be no conflict. We would say: class C2 extends C1 implements I1, I2, I3 Example: Circular [NOTE: this example is slightly different from the one given in the slides. So, see the slides also...] Many geometrical shapes have a radius , for example, of a circle, sphere, and cylinder. Suppose we wanted to define classes Circle , Sphere , Cylinder . In each case, we might have a private field radius and public methods getRadius() and setRadius() . 1 But nodes do not have references to their children, i.e. subclasses. 2 If this ‘unique parent’ constraint were not in place, and a class C were allowed to extend multiple classes (say A and B ), then it could happen that there is method conflict – superclasses A and B could contain a method with the same signature (but with different bodies). Which of these methods would an object of class C inherit? 1 COMP 250 Winter 2010 32 - interfaces April 7, 2010 We can also talk about an area for each shape, though this has different meanings for the three types of shape. So we want to define a method getArea() ....
View Full Document