What We Will Cover
Illuminations
Questions from last class?
^ top
8.1: Interfaces
Objectives
At the end of the lesson the student will be able to:
- Declare and Implement interfaces
- Use interfaces as arguments to methods
|
^ top
8.1.1: Introduction to Interfaces
- In real life, interfaces define how people interact with systems
- For example, the controls on a radio are the interface between users and the radio's internal components
- The controls allow a user to perform a limited set of operations like:
- Adjusting the volume
- Finding a radio station
- In Java, interfaces define and standardize ways that objects interact with each other
- A Java interface defines a set of methods that an object must have to interact with a system
- The next example shows an interface for a programmer-defined system with the method that any object must implement for drawing
Example Interface
- Here is an example of a simple interface:
public interface Drawable {
public static final int FILLED = 0;
public static final int UNFILLED = 1;
public void draw();
}
Provides two integer constants
Declares a single abstract method named draw()
Note that the interface does not provide any code for the method
An interface can only provide a method signature
Example Interface Implementation
- A class that implements an interface must:
- Declare that it is implementing the interface
implements Drawable
- Provide code for all the methods of the interface
- Here is an example class implementing the
Drawable interface shown above
class Shape implements Drawable {
public void draw() {
System.out.println("Drawing a Shape.");
}
}
^ top
8.1.2: Abstract Classes vs. Interfaces
- Abstract classes and interfaces have many similarities and differences
- Both abstract classes and interfaces allow you to define constants
- In addition, both abstract classes and interfaces allow you to declare abstract methods
- These similarities mean that interfaces can sometimes be used instead of an abstract class
Advantages of an Abstract Class
- An abstract class can have instance variables while an interface cannot
- An abstract class can define regular methods while interfaces can only declare abstract methods
- An abstract class can define static methods while an interface cannot
Advantages of an Interface
- A class can only inherit from one class but can directly implement many interfaces
- Any object that implements an interface can be used wherever the interface is accepted
When Will You Need Interfaces?
- Rare to code your own interfaces
- Though we will look at how to code custom interfaces
- However, you often need to implement interfaces in the Java API
- In particular, interfaces are used in coding graphical user interfaces
^ top
8.1.3: Coding Custom Interfaces
- Declaring an interface is similar to declaring a class
- You use the keyword
interface instead of class
- General syntax:
public interface InterfaceName {
dataType CONSTANT_NAME = value;
returnType methodName(optionalParameterList);
}
For example:
public interface Drawable {
public static final int FILLED = 0;
public static final int UNFILLED = 1;
public void draw();
}
Declares an abstract method named draw()
No implementation of the method can be given
Implementation is up to the implementing class
All methods are public and abstract by default
Similarly, all constants are public static final by default
- Using the keywords are optional
- Though optional, they help to document the scope
Note that interface methods cannot be declared static
Any interface method that is implemented becomes an instance method
Extending Interfaces
- You can derive new interfaces from existing one like classes can extend classes
- One added feature is that an interface can extend multiple interfaces
- Syntax:
public interface InterfaceName
[extends SuperInterface1 [, SuperInterface2]...] { }
For example, we could split our Drawable interface into two superinterfaces and one subinterface
The superinterfaces now contain the constants:
interface DrawingConstants {
public static final int FILLED = 0;
}
interface DrawingConstants2 {
public static final int UNFILLED = 1;
}
The subinterface contains the method declaration:
interface Drawable
extends DrawingConstants, DrawingConstants2 {
public void draw();
}
The new Drawable has the same capabilities as the old Drawable
^ top
8.1.4: Implementing Interfaces
- Any class can choose to implement zero or more interfaces
- Syntax:
public class ClassName [extends SuperClass]
[implements Interface1 [, Interface2]...] { }
Classes implementing an interface add the keyword implements in the class header
After the implements keyword, code a comma-delimited list of interface names
For example:
public class Map implements Drawable
Class Map must now implement the method draw()
Note that you can refer to a constant declared in the interface without the interface name if you implement the interface
int filled = UNFILLED;
A class that implements an interface must implement all methods of the interface
public class Map implements Drawable {
int filled = UNFILLED;
public void draw() {
System.out.println("Drawing a Map.");
}
}
^ top
8.1.5: Interfaces as Arguments
- A method that accepts an interface as an argument can accept any object implementing that interface
- Then you can pass any object that implements the interface as an argument
For Example
- Here is an example method that accepts the
Drawable interface
public static void drawTwice(Drawable d) {
d.draw();
d.draw();
}
We can pass any object to the drawTwice() method that implements the Drawable interface
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
interface Drawable {
public void draw();
}
class Map implements Drawable {
public void draw() {
System.out.println("Drawing a Map.");
}
}
class Shape implements Drawable {
public void draw() {
System.out.println("Drawing a Shape.");
}
}
public class ShapeApp {
public static void main(String[] args) {
Map m = new Map();
Shape s = new Shape();
drawTwice(m);
drawTwice(s);
}
public static void drawTwice(Drawable d) {
d.draw();
d.draw();
}
}
|
- Since both the
Map and Shape class implements Drawable, they must implement the draw() method
- We can send either a
Map or a Shape to the drawTwice() method
- Creates a flexible design that allows us to easily plug new classes into the system
^ top
8.1.6: Interfaces and Polymorphism
- You can implement polymorphism using interfaces rather than an abstract class
- It is also easy to mix both interfaces and abstract classes in one design
- Here is an example implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
interface Drawable {
void draw();
}
class Shape implements Drawable {
public void draw() {
System.out.println("Drawing a Shape.");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawing a Circle.");
}
}
class Rectangle extends Shape {
public void draw() {
System.out.println("Drawing a Rectangle.");
}
}
class Square extends Rectangle {
public void draw() {
System.out.println("Drawing a Square.");
}
}
class Map implements Drawable {
public void draw() {
System.out.println("Drawing a Map.");
}
}
public class Polymorph {
Shape[] s = { new Circle(), new Rectangle(),
new Square() }; //(1)
Drawable[] d = { new Shape(), new Rectangle(),
new Map() }; //(2)
public static void main(String args[]) {
Polymorph poly = new Polymorph();
poly.drawShapes();
poly.drawDrawables();
}
public void drawShapes() {
System.out.println("Draw shapes:");
for (int i = 0; i < s.length; i++) //(3)
shapes[i].draw();
}
public void drawDrawables() {
System.out.println("Draw drawables:");
for (int i = 0; i < d.length; i++) //(4)
drawables[i].draw();
}
}
|
- At (1),
shapes[] holds references to various Shape objects
- At (2),
drawables[] holds references to classes that implement Drawable interface
- Calling the
draw() method at (3) and (4) relies on polymorphism
- At runtime, dynamic lookup determines which
draw() method to use
- It is easy to add new classes to the
Shape or Drawable arrays
- There is no need to change any conditional logic
^ top
8.1.7: Summary
- An even more abstract "class" is an interface
- An interface can contain:
- Static constants
- Abstract methods
- For example:
public interface Drawable {
public static final int FILLED = 0;
public static final int UNFILLED = 1;
public void draw();
}
The advantage of an interface is that classes can implement many interfaces
Provides many of the advantages of multiple inheritance without the headaches
All methods of an interface are public and abstract by default
Similarly, all constants are public static final by default
You can extend interfaces using the extends keyword
public interface InterfaceName
[extends SuperInterface1 [, SuperInterface2]...] { }
Any class can choose to implement zero or more interfaces
When it does, it must implement all the methods of the interface
public class Map implements Drawable {
public void draw() {
System.out.println("Drawing a Map.");
}
}
A method that accepts an interface as an argument can accept any object that implements that interface
public static void drawTwice(Drawable d) {
d.draw();
d.draw();
}
You can use interfaces to implement polymorphic systems as well
^ top
Exercise 8.1
Take one minute to prepare an answer the following question:
- Which of the following statements are true about interfaces
- Members of an interface are never static
- Members of an interface can always be defined static
- Interfaces can implement variables but not methods
- Interfaces can extend any number of other interfaces
- Constants in an interface must be declared public or compilation will fail
^ top
8.2: Midterm Review
Objectives
At the end of the lesson the student will be able to:
- Describe how to prepare for the midterm exam
- Describe how to take the midterm exam
|
^ top
8.2.1: About the Midterm Exam
Important Midterm Exam Information
Date and Time: 4/06/05 @ 10:00 A.M. to 11:20:00 A.M.
Location: Room 516 (regular classroom)
|
- You must attend the exam or you will receive a score of zero (0)
- Except by prior arrangement with the instructor
- I am using WebCT to administer the test
- The exam is designed to take about one hour to complete
- However, you will have 100 minutes during the scheduled time to complete the exam
- You may have less time if you are late to the exam
- The exam is closed books and closed notes
- However, you may have one 3" x 5" card of notes for the exam
- You may use your computer, but only to take the exam in WebCT
- You may have a sheet of blank scratch paper
- You may NOT use the computer to compile or run programs
- You may NOT use the computer to view documents on the Internet
- You may NOT use a calculator or other electronic device
- You may NOT communicate with anyone but the instructor during the exam
^ top
8.2.2: Recommended Preparation
- Work through the Practice Midterm Exam questions in WebCT
- Working the problems in groups is encouraged
- Get explanations for anything you do not understand
- Review your notes and prepare your 3" x 5" card
- Review your homework assignments and solutions
- You should be prepared to write short programs
^ top
8.2.3: Exam Taking Tips
- Save after every answer -- you can always choose another answer
- If you get stuck on a question, make your best guess and return later
- If you are equally uncertain between two choices, go with first impression
- You do not need to comment code for tests and exams
- Unless specifically instructed to in the exam question
- Use the full time available
- More quiz tips: TAKING MULTIPLE –CHOICE TESTS
^ top
8.2.4: Questions and Answers
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Room Policies
| Course Info
Help
| FAQ's
| HowTo's
| Links
Last Updated: April 13 2005 @15:34:55
|