0% found this document useful (0 votes)
2 views

Lecture_08_Interface

The document provides an overview of Java interfaces, including their purpose, creation, and usage in polymorphism. It explains the difference between interfaces and abstract classes, the implementation of interfaces in classes, and the concept of shallow and deep cloning. Additionally, it covers default methods in interfaces and provides examples demonstrating the use of interfaces in various scenarios.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture_08_Interface

The document provides an overview of Java interfaces, including their purpose, creation, and usage in polymorphism. It explains the difference between interfaces and abstract classes, the implementation of interfaces in classes, and the concept of shallow and deep cloning. Additionally, it covers default methods in interfaces and provides examples demonstrating the use of interfaces in various scenarios.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Java Interface

CSIT213 Java Programming


Overview
• Introduction

• Creating and using interfaces

• Shallow and deep clone

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.

Abstract class: specific To-do methods list

Pork

Non-abstract subclass: specify how to-do the methods, respectively


9
What are interfaces? A Summary
• Interfaces define and standardize how things, such as people and systems
can interact with one another.

• An interface is designed from the point of view of interaction


- It is often used when disparate classes (i.e., unrelated classes) need to
share common methods and constants.
- Allows objects of unrelated classes to be processed polymorphically by
responding to the same method calls.
Another way to implement polymorphism besides inheritance.
- You can create an interface that describes the desired functionality, then
implement this interface in any classes that promise that functionality.

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;

public abstract void cut();

public abstract void eat();


}

interface washable {
public static final int timeLimit = 3;

public abstract void wash();

public abstract void dry();


}

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.

• Implementing an interface is like signing a contract with the compiler that


states, “I will implement all the abstract methods specified by the interface
or I will declare my class 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

abstract class NotFood implements washable {


private String name;

public NotFood(String name) { Use interface washable


No need to override this.name = name;
abstract methods }

public String toString() {


return "Name: " + name;
}
}

15
Example – concrete class Apple
Inherit abstract class Fruit

class Apple extends Fruit {


public Apple(String name, String color, int size) {
super(name, color, size);
}

public void eat() {


System.out.println("Eat apple");
}
Override eatable methods

public void cut() {


System.out.println("Cut apple");
}

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");
}

public String toString() {


return String.format("Apple %s", super.toString());
}
}

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();

Car c = new Car("ABC");


System.out.println(c);
c.dry();

19
Interface Animal in UML
implicitly public static final
implicitly public abstract

20
testInterface2.java

Example – interface Animal


interface Animal {
public String SLEEP="Zzz";
public void animalSound();
public void sleep();
}

21
Example – Pig class
class Pig implements Animal {
private String sound;
public Pig() {
sound="Wee Wee";
}

public void animalSound() {


System.out.println("The pig says: " + sound);
}

public void sleep() {


System.out.println(SLEEP);
}
}

22
Example – Duck class
class Duck implements Animal {
private String sound;

public Duck(){
sound="Quack Quack";
}

public void animalSound(){


System.out.println("The duck says: "+ sound);
}

public void sleep() {


System.out.println(SLEEP);
}
}

23
Example - testing
public class testInterface2 {
public static void main(String[] args) {
Pig p = new Pig();
p.animalSound();
p.sleep();

Duck d = new Duck();


d.animalSound();
d.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)

• Both operations need to calculate payment amount.


- For an employee, the payment refers to the employee’s salary.
- For an invoice, the payment refers to the total cost of the goods listed
on the invoice.

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.

• Both classes implement the Payable interface. Hence, a program can


invoke the method getPayment on Invoice objects and Employee
objects.

- Enables the polymorphic processing of Invoices and Employees.

27
testInterface3.java

Example – interface Payable

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;

public Invoice(int number, String desc, int total, double price) {


this.number = number;
description = desc;
quantity = total;
itemPrice = price;
}

public double getPayment() { Override getPayment()


return quantity * itemPrice;
}

public String toString() {


return String.format("Number: %d, Description: %s, Quantity: %d, Item price: %.2f,
Total: %.2f", number, description, quantity, itemPrice, getPayment());
}
}
29
Example – abstract class Employee
Use interface Payable, no
abstract class Employee implements Payable {
implementation of abstract method
private int number;
private String name;
private String dob;
private String address;

public Employee(int number, String name, String dob, String address) {


this.number = number;
this.name = name;
this.dob = dob;
this.address = address;
}

public String toString() {


return String.format("Number: %d, Name: %s, DOB: %s, Address: %s", number,
name, dob, address);
}
}

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;
}

public double getPayment() { Override getPayment()


return salary;
}

public String toString() {


return String.format("%s, Salary: %.2f", super.toString(), getPayment());
}
}

31
Interface Polymorphism
• Objects of a class that implements an interface can be treated as the
interface type.

• Thus, just as we can assign the reference of a SalaryEmployee object to a


superclass Employee variable, we can assign the reference of a
SalaryEmployee object to an interface Payable variable.

• Invoice implements Payable, so an Invoice object also is a Payable object,


and we can assign the reference of an Invoice object to a Payable variable.

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);

Invoice rec = new Invoice(100, "Bread", 3, 2.5);

//Add to a Payable list


ArrayList<Payable> payments = new ArrayList<Payable>();
payments.add(se);
payments.add(rec);

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.

• The implementing class is not required to override the interface’s default


methods, but it can if necessary.

35
Interface hierarchy

36
testInterface4.java

Example – interface Animal

interface Animal {
public String SLEEP = "Zzzz";

public void animalSound();

public default void sleep() {


A default method
System.out.println(SLEEP);
}
}

37
Example – class Animals
class Animals implements Animal {
private String sound;
private String type;

public Animals(String sound, String type) {


this.sound = sound;
this.type = type;
Override animalSound().
} Use default sleep().

public void animalSound() {


System.out.println("The " + type + " says " + sound);
}
}

38
Example – classes Pig and Duck
class Pig extends Animals {
public Pig() {
super("Wee wee", "Pig");
}
}

class Duck extends Animals {


public Duck() {
super("Quack quack", "Duck");
}
}

39
Example - testing

public class testInterface4 {


public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
Pig p = new Pig();
animals.add(p);
Duck d = new Duck();
animals.add(d);

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.

Java allows overriding method changes the return type:


• The return type of overriding method must be compatible with return
type of the overridden method.

49
OverrideAccessReturn.java

Example - More on overriding


class Animals {

protected void animalSound(){
System.out.println( "The " + type + " says " + sound);
}
public Animal getMyself(){ return this; }
}

class Pig extends Animals {



@Override
public void animalSound() { …}

@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

Example - shallow clone


class Person implements Cloneable {

public Person clone() throws CloneNotSupportedException {


return (Person) super.clone();
}
}

52
testDeepClone.java

Example - deep clone


class Person implements Cloneable {

public Person clone() throws CloneNotSupportedException {


var clonedPerson = (Person) super.clone();
clonedPerson.city = clonedPerson.city.clone();
return clonedPerson;
}
}

53

You might also like