CS计算机代考程序代写 Java SWEN20003 Object Oriented Software Development 0.5 cm Interfaces and Polymorphism

SWEN20003 Object Oriented Software Development 0.5 cm Interfaces and Polymorphism

SWEN20003
Object Oriented Software Development

Interfaces and Polymorphism

Shanika Karunasekera
.au

University of Melbourne
c© University of Melbourne 2020

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 1 / 36

The Road So Far

Subject Introduction

Java Introduction

Classes and Objects

Arrays and Strings

Input and Output

Software Tools

Inheritance and Polymorphism

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 2 / 36

Learning Outcomes

Upon completion of this topic you will be able to:

Describe the purpose and use of an interface

Describe what it means for a class to use an interface

Describe when it is appropriate to use inheritance vs. interfaces

Use interfaces and inheritance to achieve powerful abstractions

Make any class “sortable”

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 3 / 36

Interfaces

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 4 / 36

Interfaces

In the last lecture you learnt about abstract classes.

Keyword

Abstract Class: A class that represents common attributes and methods of
its subclasses, but that is missing some information specific to its
subclasses. Cannot be instantiated.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 5 / 36

Interfaces

Interfaces are vague, distant relatives of abstract classes:

Defines an “abstract” entity – can’t be instantiated

Can only contain constants and abstract methods

Defines behaviours/actions that are common across a number of
classes

A class can choose to “implement” an interface

Keyword

Interface: Declares a set of constants and/or methods that define the
behaviour of an object.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 6 / 36

Can Do

All interfaces represent a “Can do” relationship

Classes that implement an interface can do all the actions defined by
the interface

Interface names are generally called <...>able, and relate to an
action

For example, classes that implement the interface can all
be driven, because they implement the drive() method

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 7 / 36

Defining Interfaces

public interface Printable {

int MAXIMUM_PIXEL_DENSITY = 1000;

void print();

}

Methods never have any code

All methods are implied to be abstract

All attributes are implied to be static final

All methods and attributes are implied to be public

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 8 / 36

Interfaces

Keyword

interface: Defines an interface, rather than a class.

Keyword

implements: Declares that a class implements all the functionality
expected by an interface.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 9 / 36

Implementing Interfaces

public class Image implements Printable {

public void print() {

}

}

public class Spreadsheet implements Printable {

public void print() {

}

}

Concrete classes that implement an interface must implement all
methods it defines

Classes that don’t implement all methods must be abstract

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 10 / 36

Default Methods

Classes can be “forced” to have an implementation of a method, that can
then be overridden.

public interface Printable {

default void print() {

System.out.println(this.toString());

}

}

Keyword

default: Indicates a standard implementation of a method, that can be
overridden if the behaviour doesn’t match what is expected of the
implementing class.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 11 / 36

Assess Yourself

A person can wear many items of clothing and apparel, but each item can
go on a different part of a person’s body.

Implement a possible interface for this scenario, as well as one or more
implementations of the interface’s method(s), such that a hypothetical
Person object can “wear clothes”.

Bonus: Why are we using an interface for this?

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 12 / 36

Assess Yourself

public interface Wearable {

public void wear();

}

public class Clothing implements Wearable {

private String bodyPart;

public Clothing(String bodyPart) {

this.bodyPart = bodyPart;

}

public void wear() {

System.out.format(“%s is worn on your %s.\n”,

this.getClass().getName(), this.bodyPart);

}

}

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 13 / 36

Assess Yourself

public class Seatbelt implements Wearable {

private Car car;

private boolean isWorn = false;

public Seatbelt(Car car) {

this.car = car;

}

public void wear() {

this.isWorn = true;

this.car.setCanDrive(true);

}

}

Even though Clothing and Seatbelt can both be “worn”, there is no
logical relationship between them; they should not be represented using
inheritance!

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 14 / 36

Extending Interfaces

public interface Digitisable extends Printable {

public void digitise();

}

Interfaces can be extended just like classes

Forms the same “Is a” relationship

Used to add additional, specific behaviour

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 15 / 36

Sorting

What is sorting?

Arranging things in an order

What can we sort?

Any piece of data

How do we sort?

Arrays.sort(arrayOfThings);

But… How? How does Java know how to arrange Robots? Or Dogs?

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 16 / 36

String

How does Java sort an array of Strings? Why?

String[] strings = new String[]{“dragon”,

“Jon Snow”, “Game of Thrones”};

System.out.println(Arrays.toString(strings));

Arrays.sort(strings);

System.out.println(Arrays.toString(strings));

[dragon, Jon Snow, Game of Thrones]

[Game of Thrones, Jon Snow, dragon]

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 17 / 36

String

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 18 / 36

Comparable Interface

A class that implements Comparable

Can (unsurprisingly) be compared with objects of the same class

Must implement public int compareTo( object)

Can therefore be sorted automatically

The general use of will be explained in a later lecture, stay
tuned

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 19 / 36

compareTo

How does it work?

Defines a method allowing us to order objects

Compares exactly two objects, A and B

B can be a subclass of A, as long as they are both Comparable

Returns a negative integer, zero, or a positive integer if object A
(this) is “less than”, “equal to”, or “greater than” object B (the
argument)

public int compareTo(String string) {

return this.length() – string.length();

}

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 20 / 36

compareTo

Worked Example

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 21 / 36

Assess Yourself

Write a class called RandomNumber that implements the Comparable
interface.

Each RandomNumber object should have a single instance variable called
number, that is given a random integer when the object is instantiated.

When RandomNumbers are sorted, they should appear in ascending order,
according to the value of number.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 22 / 36

Comparable Interface Example

import java.util.Random;

import java.util.Arrays;

public class RandomNumber implements Comparable {

private static Random random = new Random();

public final int number;

public RandomNumber() {

this.number = random.nextInt(100);

}

public int compareTo(RandomNumber randomNumber) {

return this.number – randomNumber.number;

}

public String toString() {

return Integer.toString(this.number);

}

}

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 23 / 36

Comparable Interface Example

public static void main(String args[]) {

RandomNumber randomNumbers[] = new RandomNumber[10];

for (int i = 0; i < randomNumbers.length; i++) { randomNumbers[i] = new RandomNumber(); } System.out.println(Arrays.toString(randomNumbers)); Arrays.sort(randomNumbers); System.out.println(Arrays.toString(randomNumbers)); } [51, 90, 65, 50, 75, 67, 42, 72, 65, 49] [42, 49, 50, 51, 65, 65, 67, 72, 75, 90] Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 24 / 36 Next Level Abstraction public class Spreadsheet extends Document implements Printable, Colourable, Filterable, Comparable {

public void print() {

}

}

Classes can only inherit one class, but can implement multiple
interfaces

Inheritance and interfaces work together to build very powerful
abstractions that make creating solutions much easier

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 25 / 36

Multiple Inheritance

You: “Oh, so we can do multiple inheritance in Java!”

Me: “No, you can’t.”

You: “But you just said classes can implement multiple interfaces?”

Me: “I did. They are not the same thing.”

You: “But…”

Me: “Totally. Different. Things.”

Inheritance is for generalising shared properties between similar classes; “is a”.

Interfaces are for generalising shared behaviour between (potentially) dissimilar

classes; “can do”.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 26 / 36

Polymorphism

Inheritance

Robot robot = new WingedRobot(…);

Interfaces

Comparable comparable = new Robot(…);

Subtype polymorphism applies to interfaces!

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 27 / 36

Assess Yourself

Interface or Inheritance?

All Dogs can bark.

Both?

Needs more context…

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 28 / 36

Assess Yourself

Interface or Inheritance?

All Animals, including Dogs and Cats can make noise.

Inheritance

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 29 / 36

Assess Yourself

Interface or Inheritance?

All Animals and Vehicles can make noise.

Interface

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 30 / 36

Assess Yourself

Interface or Inheritance?

All classes can be compared with themselves.

Interface

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 31 / 36

Assess Yourself

Interface or Inheritance?

All Characters in a game can talk to the Player.

Inheritance

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 32 / 36

Assess Yourself

Interface or Inheritance?

Some GameObjects can move, some can talk, some can be opened,
and some can attack.

Interface

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 33 / 36

Interface or Inheritance?

Inheritance:

Represents passing shared information from a parent to a child

Fundamentally an “Is a” relationship; a child is a parent, plus more;
hierarchical relationship

All Dogs are Animals

Interface:

Represents the ability of a class to perform an action

Fundamentally a “Can do” relationship; a Comparable object can be
compared when sorting

Strings can be compared and sorted

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 34 / 36

Metrics

A Student is specified by a first and last name, a student ID, and a list of
subjects. When Students are sorted, they should appear in increasing student
number order.

A Subject is specified by a name, subject code, and a list of students. When
Subjects are sorted, they should appear in order of ascending subject code.

A Course is specified by a name, a course code, a list of (possible) subjects, and
a list of students. When Courses are sorted, they should appear in order of
ascending course code.

Implement appropriate compareTo methods for each class, and implement the

Enrollable interface such that a Student can enrol in both a Subject and a

Course.

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 35 / 36

Lecture Objectives

After this lecture you will be able to:

Describe the purpose and use of an interface

Describe what it means for a class to use an interface

Describe when it is appropriate to use inheritance vs. interfaces

Use interfaces and inheritance to achieve powerful abstractions

Make any class “sortable”

Shanika Karunasekera SWEN20003 c© University of Melbourne 2020 36 / 36