Download presentation
Presentation is loading. Please wait.
1
Java Interfaces Overview Java Interfaces: A Definition.
Declaring Interfaces in Java Programs. Interfaces: An Example. Interfaces: Some Rules. Interfaces Versus Abstract Classes. Interfaces and Multiple Inheritance. Applications of Interfaces. Limitations of Interfaces. A Complete Program. Coming Next: Inner Classes. Java Interfaces
2
Inheritance-Classes Interfaces
class B extends A {………} class C extends A{………..} B C Several classes are allowed to inherit from a single class E D X F A single class may not inherit from multiple classes. Multiple inheritance is forbidden in Java Java Interfaces
3
Inheritance-Classes Interfaces (Cont’d)
Class F extends D Implements E F Class F inherits from class D and implement the abstract methods defined by the interface E Java Interfaces
4
Interfaces ….otherMethod( ). startEngine( ); stopEngine( );
class Automobile implements Driveable ….otherMethod( ). startEngine() stopEngine() accelerate() turn() interface Driveable{ startEngine( ); stopEngine( ); accelerate( ); turn( ); } // End of Driveable interface class Tractor implements Driveable cutGrass()…… startEngine() stopEngine() accelerate() turn() Java Interfaces
5
Java Interfaces: A Definition
A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. interface interfaceName { specifications of a set of methods } A class can implement this interface by providing code for all the specified methods. class classname implements interfaceName { bodies for the interface methods own data and methods } Java Interfaces
6
Java Interfaces: A Definition (Cont’d)
An interface is a named collection of method definitions (without implementations). The interface declaration can have: An interface looks very much like a class, except all of its methods must be abstract and all of its data(if any) must be static final. public abstract methods. public static final constants interface interfaceName { specifications of a set of methods } A class can implement this interface by providing code for all the specified methods. class classname implements interfaceName { bodies for the interface methods own data and methods } Java Interfaces
7
Declaring Interfaces in Java Programs
Consider the following Java code: interface Movable { boolean start(); void stop(); boolean turn (int degrees); double fuelRemaining(); boolean changeSpeed (double kph); } Interface The above code defines an interface called Movable. This looks like an abstract class! (NOT REALLY!) abstract class Movable { abstract boolean start(); abstract void stop(); abstract boolean turn (int degrees); abstract double fuelRemaining(); abstract boolean changeSpeed (double kph); } Abstract Class Java Interfaces
8
Interfaces: An Example
The class Lazy defined below implements the interface Sleeper. class Lazy implements Sleeper { int duration; public void wakeUp() { for(int i = 0; i < ONE_HR; i++) ; System.out.println(“I am awake()!!!”); } // End of wakeUp() method } // End of class Lazy public class TestLazy { public static void main(String[] args) { Lazy ref1 = new Lazy(); ref1.wakeUp(); } // End of main() method } // End of class TestLazy Class Lazy Implementing Sleeper Using Interface Constant Field interface Sleeper { void wakeUp(); long ONE_HR = 36000; } // End of interface Sleeper Definition of Sleeper Interface Java Interfaces
9
Interfaces: Some Rules
A careful look at the body of the interface Sleeper will point out the following: interface Sleeper { void wakeUp(); long ONE_HR = 36000; } // End of interface Sleeper The method declaration for the method wakeUp() is followed by a semicolon (;) because an interface does not provide implementations for the methods declared within it. All methods declared in an interface are implicitly public and abstract. The use of these modifiers on a method declaration in an interface is discouraged as a matter of style. An interface can contain constant declarations in addition to method declarations. The Sleeper interface declares one constant that is a useful argument to the implementing class Lazy. All constant values defined in an interface are implicitly public, static, and final. The use of these modifiers on a constant declaration in an interface is discouraged as a matter of style. Any class can use an interface's constants from the name of the interface, like this: Sleeper.ONE_HR; Classes that implement an interface can treat the constants as though they were inherited. This is why the class Lazy uses ONE_HR directly when implementing the abstract method wakeUp(): for(int i = 0; i < ONE_HR; i++) Java Interfaces
10
Interfaces: Some Rules (Cont’d)
You may not use the private and protected modifiers when declaring members of an interface. See the Sleeper definition and compiler message below: interface Sleeper { private void wakeUp(); public long ONE_HR = 36000; } // End of interface Sleeper C:\ics_courses\semester002\Ghouti_Slides\Lecture9_Programs\TestLazy.java:22: Interface methods can't be native, static, synchronized, final, private, or protected : private void wakeUp(); ^ 1 error Note: Previous releases of the Java platform allowed you to use the abstract modifier on interface declarations and on method declarations within interfaces. However this is unnecessary, since interfaces and their methods are implicitly abstract. You should no longer be using abstract in your interface declarations or in your method declarations within interfaces. x Java Interfaces
11
Interfaces Versus Abstract Classes
Question: Why Can't I Just Use an Abstract Class instead on an Interface? Answer: At this point, many programmers wonder how an interface differs from an abstract class. An interface is simply a list of unimplemented, and therefore abstract, methods. Wouldn't the following Sleeper class do the same thing as the Sleeper interface? abstract class Sleeper { public abstract void wakeUp(); long ONE_HR; } NO. The two are not equivalent. If Sleeper is an abstract class, then all objects that wish to use the functionality of the Sleeper class must be instances of a class inherited from Sleeper. However, many objects that wish to use Sleeper already have a superclass. But Java doesn't support multiple inheritance. Hence, you use an interface instead. This is the practical explanation of the problem. The conceptual explanation is this: Sleeper should not force a class relationship on its users. It doesn't matter what their class is. It simply matters that they implement a specific method. Java Interfaces
12
Interfaces and Multiple Inheritance
Often interfaces are considered as an alternative to multiple class inheritance. While interfaces may solve similar problems, interface and multiple class inheritance are quite different issues, in particular: A class inherits only constants from an interface. A class cannot inherit method implementations from an interface. The interface hierarchy is independent of the class hierarchy. Classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance. Yet, Java does allow multiple interface inheritance. That is, an interface can have multiple superinterfaces. Interface3 Interface1 Interface2 interface Interface3 extends Interface1, Interface2 { specifications of a set of methods } Java Interfaces
13
Applications of Interfaces
You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following purposes: Capturing similarities between unrelated classes without artificially forcing a class relationship. Declaring methods that one or more classes are expected to implement. Revealing an object's programming interface without revealing its class. All methods within an interface must be abstract. A class can inherit from only one abstract superclass, but it can implement any number of interfaces An interface specifies only the messages to which an object can respond; an abstract class can include methods that contain the actual behavior that the object performs when those messages are received. You create an interface when you want a class to implement behavior from more than one superclass. Java Interfaces
14
Limitations of Interfaces
Warning! Interfaces Cannot Grow Suppose you want to add some functionality to Sleeper for its new version. For example, the Sleeper interface will include a beep() method as follows: interface Sleeper { void wakeUp(); void beep(); long ONE_HR = 36000; } New Functionality Added to Sleeper However, if you make this change to Sleeper, all classes that implement the old Sleeper will break because they don't implement the interface anymore! Programmers relying on this interface will face troubles. Tip: Try to anticipate all uses for your interface earlier and specify it completely from the beginning. Java Interfaces
15
A Complete Program interface Instrument { int i = 5; // static & final
// Cannot have method definitions: void play(); // Automatically abstract and public String what();// Automatically abstract and public void adjust();// Automatically abstract and public } Java Interfaces
16
A Complete Program (cont)
Class Wind implements Instrument{ public void play() { System.out.println("Wind.play()"); } public String what() { return "Wind"; public void adjust() { } // End of class Wind class Percussion implements Instrument { System.out.println("Percussion.play()"); return "Percussion"; } // End of class Percussion class Stringed implements Instrument { System.out.println("Stringed.play()"); return "Stringed"; class Brass extends Wind { System.out.println("Brass.play()"); System.out.println("Brass.adjust()"); Java Interfaces
17
A Complete Program (Cont’d)
public class TestInstruments { // Doesn't care about type, so new types // added to the system still work right: static void tune(Instrument i) { i.play(); } static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); public static void main(String[] args) { Instrument[] orchestra = new Instrument[5]; int i = 0; // Upcasting during addition to the array: orchestra[i++] = new Wind(); orchestra[i++] = new Percussion(); orchestra[i++] = new Stringed(); orchestra[i++] = new Brass(); orchestra[i++] = new Woodwind(); tuneAll(orchestra); } // End of main() method } // End of class TestInstruments class Woodwind extends Wind { public void play() { System.out.println( "Woodwind.play()"); } public String what() { return "Woodwind"; } // End of class Woodwind Java Interfaces
18
Previous Example UML Structure
Java Interfaces
19
Abstract Classes Versus Interfaces
Data must be constants Can have all types of data Methods signature without implementation Can have concrete methods Instance methods not allowed ok Can not be instantiated Can it be extended? Not really, but can be implemented instead Can be extended Java Interfaces
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.