510 likes | 534 Views
Java Interfaces. Warm-up: What is an abstract class? What is type casting?. Abstract Class Review. Assume the following partial declarations have been made, with default (no parameter) constructors for the classes. public abstract class Player public class ComputerPlayer extends Player;
E N D
Java Interfaces Warm-up: What is an abstract class? What is type casting?
Abstract Class Review Assume the following partial declarations have been made, with default (no parameter) constructors for the classes. public abstract class Player public class ComputerPlayer extends Player; public class SmartComputerPlayer extends ComputerPlayer; Consider the following declarations. ComputerPlayer playerA = new SmartComputerPlayer(); Player playerB = new SmartComputerPlayer(); Player playerC = new Player(); Which of these declarations will compile correctly? A. I only B. II only C. III only D. I and II E. II and III
Review Question Consider the following declarations. public class NoiseMaker { public NoiseMaker(String sound) { System.out.print(sound); } public void makeNoise() { System.out.print(" boom"); } } public class LoudNoiseMaker extends NoiseMaker { public LoudNoisemaker(String sound) { super(sound); } public void makeNoise() { super.makeNoise(); super.makeNoise(); } } The following method is in a client class. public void doIt() { NoiseMaker boomBox = new LoudNoiseMaker("ring"); boomBox.makeNoise(); } What happens when these classes are compiled and the method doIt is executed?
Learning Objectives • Be able to define an Interface • Understand how a class implements an interface • Understand the similarities and differences between interfaces, classes and abstract classes. • Know when and how to type cast • Understand default access modifiers
Inheritance • Java has single inheritance. • So a child class can only have one parent class • Interfaces gives you a tool to get around this limitation
Java Allows only Single Parent • i.e. lets classes have only one supercalss • Because multiple inheritance can cause problems • Consider a Person class with a resolveConflict() method.
Problems with Multiple Inheritance • Governor might override resolveConflict() to mediate a solution • Terminator might override resolveConflict() in a different manner. • What is a Governator to do? • Which superclass resolveConflict() method does it inherit? • This is known as diamond Inheritance.
Interface • To avoid diamond inheritance Java does not allow extending more than one class • Instead you can use an interface which allows you to specify behavior (methods) that we want to have without actually specifying the exact implementation (code)
Interface … • An interface is like a class except… • The keyword interface is used instead of class • All of its methods are body-less (abstract) • It has no instance variables • It cannot be instantiated • An interface is like a contract, protocol, role, or point of view • Code written for an interface type works with any object whose class implements it. • It is assumed that all of the subclasses have the methods listed in the interface (e.g. sit and stand)
A Class implements an Interface • A class that implements an interface • Must provide concrete methods for each interface method • May have additional methods • May implement multiple interfaces
Example: Trainable Interface • Lion lion = new Lion(); • Dog dog = new Dog(); • Trainable beast;// Can point to any object that implements the Trainable Interface. • beast = lion; • beast.sit();// Calls the Lions sit method • beast = dog; • beast.sit();// Calls the Dog’s sit method
Abstract class vs. Interface • When a partial implementation is a feasible, abstract classes make sense as they can provide some functionality with the methods • Pure abstract classes (with all abstract methods) in Java are functionally equivalent to an interface, but restricted to single inheritance. • Java will allow you to implement more than one interface. • You can only extend one class. • You can use modifiers (e.g. private, protected) in an abstract class though. Interfaces are always public. • Also Interfaces can only have constants (implicitly public, static and final)
Designing Interfaces • Most of the time you will use Java’s interfaces • You would want an interface if you want classes of carious types to all have a certain set of capabilities.
Interface Definitions • A list of constant and method declarations that DO NOT include implementation. (All headers, not code) • For a class to implement an interface, it must define all of the methods.
Another Example Every class that implements RuleSet must have these methods public class CheckersRules implements RuleSet { // one implementation public boolean isLegal(Move m, Board b) { ... } public void makeMove(Move m) { ... } } public class ChessRules implements RuleSet { ... } // another implementation public class LinesOfActionRules implements RuleSet { ... } // and another Client code Example RuleSet rulesOfThisGame = new ChessRules(); This assignment is legal because a rulesOfThisGame object is a RuleSet object if (rulesOfThisGame.isLegal(m, b)) { makeMove(m); } This statement is legal because, whatever kind of RuleSet object rulesOfThisGame is, it must have isLegal and makeMove methods
Interface Syntax interface InterfaceName { constant definitions method declarations (without implementations). } Access modifies, a return type and a parameter list (method signature)
Implementing an Interface public class SomeClass extends SomeParent implements interfaceName { } If a class definition omits extends SomeParent, what class does it extend?
public interface MyInterface { public static final int ACONSTANT = 32; public static final double PI = 3.14159; public void methodA( int x ); public double methodB(); } Example In an Interface the methods are public by default and the constants are public static final by default. So both of these declarations are the same. public interface MyInterface { int ACONSTANT = 32; double PI = 3.14159; void methodA( int x ); double methodB(); }
interface MyInterface { public static final int ACONSTANT = 32; public static final double PI = 3.14159; public void methodA( int x ); public double methodB(); } Example Note: The default access modifier for interfaces and classes is accessible to the package (other classes in the same folder)
Default Access: What if there is no public, private, protected? ‘Default access’ is equivalent to ‘package private’, only accessible to classes in the same package (folder) The only 'exception' to this is method declarations in an interface, which simply are always public and don't need to be prefixed.
Is this Interface Correct? interface SomeInterface { public final int x = 32; public double y; public double addup( ); }
Implement Interfaces A class definition must always extend one parent, but it can implement zero or more interfaces: public class SomeClass extends Parent implements SomeInterface { class definition body } The body of the class definition is the same as always. However, since it implements an interface the body must have a definition of each of the methods declared in the interface. The class definition can use access modifiers as usual. Here is a class definition that implements three interfaces: public class BigClass extends Parent implements InterfaceA, InterfaceB, InterfaceC { class definition body } Now BigClass must provide a method definition for every method declared in the three interfaces (InterfaceA, InterfaceB and InterfaceC). Here is another class definition: public class SmallClass implements InterfaceA { class definition body } Any number of classes can implement the same interfaces
Another Example • Example Problem • Let us create a database program for a store. The store sells: • Goods, each of which has the attributes: • description • price • The types of goods are: • Food—with an attribute (instance variable) "calories". Food objects are not taxable. • Toy—with an attribute "minimumAge". Toy objects are taxable. • Book—with an attribute "author". Book objects are taxable. • There are many things that are taxable that are not goods, such as services or entertainment. Also, not all goods are taxable. So we want to have the concept "taxable" as a separate concept, not part of the concept of Goods. Here is what the concept Taxable looks like: • A Taxable item, • has a taxRate of 6 percent, • has a calculateTax() method. • When implemented in Java, these concepts will appear as classes and an interface
(Design question: ) Decide on an implementation for each concept: • According to the picture, • What method(s) will Food have? • What method(s) will Toy have?
Taxable Interface Code Break: Write the code for the Taxable Interface
Fill in Goods Enter the code into BlueJ
Fill in the Book class Code in BlueJ
Application Could these 4 objects be kept in an array? What would the array type be? Write the Store application and test.
Array of Goods Since Goods has a display() method, then this method can be called without type casting.
Interface as a Type calculateTax() is a method in Taxable, and the reference (pointer) is of type Taxable you do not need to type cast to call it. • When do you typecast? • When the method is not defined in the reference’s class. • When you cast a parent reference to a child (or legal non parent) reference. • Child child = (Child) parent; Can you call item1.display()?
When do you typecast? • When the method is not defined in the reference’s class. • When you cast a parent reference to a child (or legal non parent) reference. Nope public static void main ( String[] args ) { Taxable item1 = new Book ( "Emma", 24.95, "Austin" ); System.out.println( "Tax on item 1 "+ item1.calculateTax() ); ((Book)item1).display(); } Since display() is not defined in Taxable, you need to type cast it in order to call this method.
Typecast? Where… • When do you typecast? • When the method is not defined in the reference’s class. • When you cast a parent reference to a child (or legal non parent) reference.
Typecast or No? • When do you typecast? • When the method is not defined in the reference’s class. • Child (or legal non parent) pointing at parent
More Interface Facts!!!!!!! • The public access specifier indicates that the interface can be used by any class in any package. • If you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package (folder) as the interface. • There are features of interfaces that the example did not show: A class can implement several interfaces: • class SomeClass extends SomeParent implements InterfaceA, InterfaceB, InterfaceC { } Now SomeClass must implement all the methods listed in all the interfaces. Could the interfaces contain several definitions of the same constant?
No Duplicate Constants!!! • However, it is OK if two interfaces ask for the same method. A class that implements both interfaces only needs to provide one complete method definition to satisfy both interfaces. • An interface can be made public. In fact, this is usually what is done. When a class or interface is public it must be the only public class or interface in the file that contains it. (These notes have been avoiding public classes so that the "copy paste save and run" method can be used with just one file.) • A public interface can be implemented by any class in any file. Many graphical user interface components implement public interfaces. You must use them to work with the GUI features of Java.
Review • What is an interface? • Can you instantiate an interface? • Can a class have several interfaces? • What are differences between and interface and an abstract class? • What are differences between an interface and a concrete class? • What is type casting? • When do you need to type cast ()?
Assume that the following partial declarations have been made, with default constructors for the classes. public interface Controller public class Widget implements Controller public class Thingy extends Widget Consider the following declarations. I. Widget myThing = new Thingy(); II. Controller myWidge = new Thingy(); III. Controller myControl = new Controller(); Which of these declarations will compile correctly?
Assume that the following partial declarations have been made, with default constructors for the classes. public interface Controller public class Widget implements Controller public class Thingy extends Widget Consider the following declarations. I. Widget myThing = new Thingy(); II. Thingy myWidge = new Widget(); III. Controller myControl = new Thingy(); Which of these declarations will compile correctly?
Which of the following statements about an interface is true? A. An interface can only have a default (no parameter) constructor. B. An interface can only have instance variables that are private. C. An interface can only have instance variables that are public. D. An interface can only have methods that are private. E. An interface can only have methods that are public.
Which of the following statements about an abstract class is true? A. An abstract class can only have a default (no parameter) constructor. B. An abstract class cannot have instance variables. C. An abstract class can only have methods that are public. D. An abstract class can have some methods that are implemented and some that are not. E. An abstract class can only have methods that are declared abstract and are not implemented.
Consider the following declarations, public interface Controller { 1 void doIt(); } public class Widget implements Controller { 2 private double myValue; public Widget() { myValue = 10; } public void doIt() { System.out.println( 2.0 * myValue); } } public class Thingy extends Widget{ public void doIt() { • System.out.println( 3.0 * myValue); } } public class Client { public void doSomething() { 4 Controller myControl = new Thingy(); myControl.doIt(); } } You attempt to compile and run these classes (with a class that correctly calls the Client doSomething method). Which of the following best describes the outcome? A. The code does not compile because in line 1 the doIt method is not declared public. B. The code does not compile because the class Widget cannot have a private instance variables that is not already declared in the interface Controller, as it does in line 2. C. The code does not compile because the variable myValue cannot be accessed within the class Thingy, as it is in line 3. D. The code does not compile because an instance of class Thingy is not type-compatible with Controller, as indicated in line 4. E. The code compiles and runs with the value 30 output when a call to doSomething is made.
Summarize • Differences and similarities between… • Concrete classes • Abstract classes • Interfaces • When do you need to type cast? • Default access modifier summary.