Lecture_08_Interface
Lecture_08_Interface
2
Introduction
• “is-a” relationship between classes is represented by inheritance.
– Subclass inherits from superclass.
• Interaction between a class and the outside world is described by interface.
– Interaction is through class methods, which form the interface of a class.
• Buttons on a TV are the interface between users and internal devices.
– Design your system from another point of view while still allowing
polymorphism.
• Implementing an interface guarantees that a class provides a set of behaviors.
– Enforced by the compiler.
– All methods defined by an interface must be implemented in a class that
implements this interface.
3
A radio interface
The interface specifies what operations a radio performs but does not specify how
the operations are performed.
• Can perform only a limited set of operations (e.g., change the station,
adjust the volume, choose between AM and FM)
• Different radios may implement the controls in different ways (e.g., using
push buttons, dials, voice commands).
• The interface specifies what operations a radio must permit users to
perform but does not specify how the operations are performed.
4
Fruit and Vegetable
Without interface, we must create a superclass to enable polymorphism.
• Move common methods, e.g., cut, eat, to the superclass.
• The introduced relationship can be unnecessary.
5
Fruit, Vegetable and Meat
6
Interface
Pork
7
Interfaces
Pork
8
Interfaces vs. abstract class
• Methods in interface are generic
for all classes.
• Methods in abstract classes are
Interface: generic To-do methods list
specific to a class hierarchy.
Pork
10
Create an interface
• An interface declaration begins with the keyword interface and contains
only constants, abstract, default, and static methods.
• All interface members must be public. Except for static methods, which
can be private.
• Interfaces may not specify any implementation details, such as concrete
method implementations.
• Basic functionality can be implemented in static/default methods.
• All methods declared in an interface are implicitly public abstract
methods by default.
• All fields are implicitly public, static and final.
• To distinguish from a class, the name of an interface often uses an
adjective but not a noun.
11
testInterface1.java
Example - interfaces
interface eatable {
public static final int timeLimit = 7;
interface washable {
public static final int timeLimit = 3;
12
Using Interfaces
• To use an interface, a concrete class must specify that it implements the
interface and must implement each abstract method in the interface with
a specified signature.
- Add the implements keyword and the name of the interface to the end
of your class declaration’s first line.
- A class can implement multiple interfaces at the same time as long as it
conducts all methods declared in the interfaces
• A class that does not implement all the abstract methods of the interface is
abstract and must be declared abstract.
13
Example – abstract class
abstract class Fruit implements eatable, washable {
private String name;
private String color; Use both interfaces
private int size;
No need to
override public Fruit(String name, String color, int size) {
abstract
methods
this.name = name;
this.color = color;
this.size = size;
}
public String toString() {
return String.format("Name: %s, Color: %s, Size: %d",
name, color, size);
}
}
14
Example – abstract class
15
Example – concrete class Apple
Inherit abstract class Fruit
16
Example – concrete class Apple
public void wash() {
System.out.println("Wash apple");
}
Override washable methods
public void dry() {
System.out.println("No need to dry apple");
}
17
Example – concrete class Car
class Car extends NotFood { Inherit abstract class NotFood
public Car (String name) {
super(name);
}
public void wash() {
System.out.println("Wash car");
}
Override washable methods
public void dry() {
System.out.println("Dry car");
}
public String toString() {
return "Car " + super.toString();
}
}
18
Example - testing
Apple a = new Apple("Delicious", "Red", 2);
System.out.println(a);
a.cut();
a.dry();
System.out.println("Eatable time limit = " + eatable.timeLimit);
…
Beef mb = new Beef("Mignon", "Steak");
System.out.println(t);
mb.cut();
mb.dry();
19
Interface Animal in UML
implicitly public static final
implicitly public abstract
20
testInterface2.java
21
Example – Pig class
class Pig implements Animal {
private String sound;
public Pig() {
sound="Wee Wee";
}
22
Example – Duck class
class Duck implements Animal {
private String sound;
public Duck(){
sound="Quack Quack";
}
23
Example - testing
public class testInterface2 {
public static void main(String[] args) {
Pig p = new Pig();
p.animalSound();
p.sleep();
24
Developing a Payable Hierarchy
• Suppose that a company wishes to perform several accounting operations
in a single account payable application
- Calculating the salary that must be paid to each employee
- Calculate the reimbursement due on invoices (i.e., bills for goods
purchased)
25
Payable Hierarchy
26
Developing a Payable Hierarchy
• Classes Invoice and Employee both represent things for which the
company must be able to calculate a payment amount.
27
testInterface3.java
interface Payable {
public abstract double getPayment();
}
28
Example – class Invoice
class Invoice implements Payable { Use interface Payable
private int number;
private String description;
private int quantity;
private double itemPrice;
30
Example – class SalaryEmployee
class SalaryEmployee extends Employee { Inherit Employee
private double salary;
public SalaryEmployee(int number, String name, String dob, String address, double
salary) {
super(number, name, dob, address);
this.salary = salary;
}
31
Interface Polymorphism
• Objects of a class that implements an interface can be treated as the
interface type.
32
Example - testing
public class testInterface3 {
public static void main(String[] args) {
SalaryEmployee se = new SalaryEmployee(12345, "Alice", "10-01-1995", "12 Ocean
road Wollongong NSW 2500", 85000.5);
for(Payable p:payments)
System.out.println(p);
}
}
33
Default interface methods
• Prior to Java SE 8, interface methods could be only public abstract
methods.
- An interface specified what operations an implementing class must
perform but not how the class should perform them.
• In Java SE 8, interfaces also may contain public default methods with
concrete default implementations that specify how operations are
performed when an implementing class does not override the methods.
• If a class implements such an interface, the class also receives the
interface’s default implementations (if any).
• To declare a default method, place the keyword default before the
method’s return type and provide a concrete method implementation.
34
default Interface Methods
• Any class that implements the original interface will not break when a
default method is added.
- The class simply receives the new default method.
35
Interface hierarchy
36
testInterface4.java
interface Animal {
public String SLEEP = "Zzzz";
37
Example – class Animals
class Animals implements Animal {
private String sound;
private String type;
38
Example – classes Pig and Duck
class Pig extends Animals {
public Pig() {
super("Wee wee", "Pig");
}
}
39
Example - testing
for(Animal a:animals) {
a.animalSound();
a.sleep();
}
}
}
40
Some common interfaces of Java API
41
Some common interfaces of Java API
42
Class Object’s methods
43
Class Object’s methods
44
Class Object’s methods
45
Shallow and deep clone (copy)
1. Shallow Cloning
This is the default cloning strategy provided by Object.clone(). The clone() method of the
Object class creates a new instance and copies all fields of the object to that new instance
(either it is primitive or a reference). The problem is that, for reference variables, only reference
itself get copied to the cloned instance. Therefore, the reference variables of both instances
(the original instance and the cloned instance) will point to the same object.
2. Deep Cloning
Deep cloning means cloning everything from one instance to another instance. To achieve this,
we need to override the clone() method to provide our own cloning strategy. We can do it by
implementing the Cloneable interface and overriding the clone() method in our object. The key
is to let reference variables in the cloned instance point to cloned objects, instead of the same
objects shared by the original instance.
46
Shallow clone
47
Deep clone
48
More on overriding
The access modifier of an overriding method must provide at least as much
access as the overridden method, as follows:
• If the overridden method is public, then the overriding method must be
public; otherwise, a compile-time error occurs.
• If the overridden method is protected, then the overriding method must
be protected or public; otherwise, a compile-time error occurs.
49
OverrideAccessReturn.java
@Override
public Pig getMyself(){ return this; }
}
50
Interface Cloneable
• A class implements the Cloneable interface to indicate to the Object.clone() method
that it is legal for that method to make a field-for-field copy of instances of that class.
• Invoking Object's clone method on an instance that does not implement the
Cloneable interface results in the exception CloneNotSupportedException being
thrown.
– The class Object does not itself implement the interface Cloneable.
• By convention, classes that implement this interface should override Object.clone
(which is protected) with a public method.
• Cloneable is a marker interface.
– It does not contain any method or variable.
51
testShallowClone.java
52
testDeepClone.java
53