04 Interfaces
04 Interfaces
Programming II
Interface
1
Java Interfaces
• A Java Interface is a formal way for a class to promise to implement
certain methods. We say that a class implements an interface if it
provides these methods
• Interface:
• Is defined by the keyword interface (rather than class)
• It defines methods (as many as you like), but does not give method
bodies (the executable statements that make up the method)
• All abstract, default, and static methods in an interface are implicitly
public, so you can omit the public modifier.
• Notice that an interface is not a class. You cannot create an
instance of an interface.
2
Defining an Interface
• Defining a Java Interface:
public interface Set<E> {
public void insert(E e);
public void clear();
public boolean contains(E o);
public boolean isEmpty();
public boolean remove(E o);
public int size();
}
3
Implementing an Interface
• A class is said to “implement” an interface if it provides
definitions for these methods
6
Comparable Interfaces
• The Comparable interface specifies a method called compareTo that
takes an object as a parameter and returns a negative integer, zero, or a
positive integer as the current object is less than, equal to, or greater than
the specified object
• Have we seen classes implementing this interface? Yes!
• String
• Integer
• Double
• All primitive wrapper classes implement Comparable
• By using interfaces a function like Collections.sort() can sort an ArrayList
of objects that implement the Comparable interface. For example, an
ArrayList of Integers, of Strings, etc.
• Can Collections.sort() sort an ArrayList of your own objects (e.g., ArrayList
of Cars?) Yes! Just make the Car class implement the Comparable
interface
7
Multiple Inheritance
• There are many situations where a simple class hierarchy is not adequate
to describe a class’ structure
• Example: Suppose that we have our class hierarchy of university people
and we also develop a class hierarchy of athletic people:
Person AthleticPerson
HeadCoach AssistantCoach
StudentAthlete
9
Multiple Inheritance with Interfaces
• Java lacks multiple inheritance, but there is an alternative
What public methods do we require of an Athlete object?
• String getSport( ): Return the athlete’s sport
• boolean isAmateur( ): Does this athlete have amateur status?
• We can define an interface Athlete that contains these methods:
public interface Athlete {
public String getSport( );
public boolean isAmateur( );
}
• Now, we can define a StudentAthlete that extends Student and
implements Athlete
10
Multiple Inheritance with Interfaces
• StudentAthlete extends Student and implements Athlete:
public class StudentAthlete extends Student implements Athlete
{
private String mySport;
private boolean amateur;
// … other things omitted
public String getSport( ) { return mySport; }
public boolean isAmateur( ) { return amateur; }
}
• StudentAthlete can be used:
• Anywhere that a Student object is expected (because it is derived
from Student)
• Anywhere that an Athlete object is expected (because it implements
the public interface of Athlete)
• So, we have effectively achieved some of the goals of multiple
inheritance, by using Java’ single inheritance mechanism
11
Common Uses of Interfaces
• Interfaces are flexible things and can be used for many purposes in
Java:
• A work-around for Java’s lack of multiple inheritance.
(We have just seen this.)
• Specifying minimal functional requirements for classes (This is
its principal purpose.)
• For defining groups of related symbolic constants.
(This is a somewhat unexpected use, but is not uncommon.)
12
Using Interfaces for Symbolic Constants
• In addition to containing method declarations, interfaces can contain
constants, that is, variables that are public final static.
interface OlympicMedal {
static final String GOLD = "Gold";
static final String SILVER = "Silver";
static final String BRONZE = "Bronze";
}
13
Default Methods
• Java 8 introduces “Default Method”, a new feature
• Add new methods to the interfaces without breaking the
existing implementation of these interface.
public interface A {
public void m1();
default public void m2 {
println("default m2”;
}
}
public class B implements A {
public void m1() {…}
}
B b = new B();
b.m2(); // print “default m2”
14
Abstract classes versus interfaces
• After introducing Default Method, it seems
that interfaces and abstract classes are same.
• However, they are still different concept in Java 8.
• Abstract class can define constructor. They can have a
state associated with them.
• default method can be implemented only in the terms of
invoking other interface methods, with no reference to a
particular implementation's state.
• Both use for different purposes and choosing between
two really depends on the scenario context.
15
Multiple Inheritance Ambiguity Problems
Since java class can implement multiple interfaces and
each interface can define default method with same method signature,
therefore, the inherited methods can conflict with each other.
public interface A {
default int m1(){
A:m1 B:m1
return 1;
}
}
public interface B { C:m1
default int m1(){
Return 2;
} This code will fail to
} compile
public class C implements A, B
{
} 16
Interface Hierarchies
17
Quiz 1: True /False
An interface can contain following type of
members:
• public, static, final fields (i.e., constants)
• default and static methods with bodies
A. True
B. False
18
Quiz 1: True /False
An interface can contain following type of
members:
• public, static, final fields (i.e., constants)
• default and static methods with bodies
A. True
B. False
19
Quiz 2: True /False
A class can implement multiple interfaces and
many classes can implement the same interface.
A. True
B. False
20
Quiz 2: True /False
A class can implement multiple interfaces and
many classes can implement the same interface.
A. True
B. False
21
Quiz 3: What is the output?
abstract class Demo{
public int a;
public Demo(){ a = 10; }
abstract public void set();
abstract final public void get();
}
class Test extends Demo{
public void set(int a){this.a = a;}
final public void get(){
System.out.println("a = " + a);
}
public static void main(String[] args){
Test obj = new Test();
obj.set(20); A. a = 10
obj.get(); } B. a = 20
} C. Compile error
22
Quiz 3: What is the output?
abstract class Demo{
public int a;
public Demo(){ a = 10; } Final method can’t be
abstract public void set(); overridden. Thus, an
abstract final public void get(); abstract function can’t be
} final.
class Test extends Demo{
public void set(int a){this.a = a;}
final public void get(){
System.out.println("a = " + a);
}
public static void main(String[] args){
Test obj = new Test();
obj.set(20); A. a = 10
obj.get(); } B. a = 20
} C. Compile error
23
Quiz 4:
24
Quiz 4:
25
Quiz 5:
26
Quiz 5:
27