49
Inheritance and Interfaces Advanced Object Orientation Tobias Andersson Gidlund [email protected] January 14, 2015 Department of Computer Science Inheritance and Interfaces 1(49)

forel2

Embed Size (px)

DESCRIPTION

Java

Citation preview

Page 1: forel2

Inheritance and Interfaces

Advanced Object Orientation

Tobias Andersson Gidlund

[email protected]

January 14, 2015

Department of Computer Science

Inheritance and Interfaces 1(49)

Page 2: forel2

Agenda

Inheritance

Understanding

Semantics

Inheritance in Java

Creating objects

Polymorphism

Substitution

Late binding

Interfaces

Using a predefined interface

Department of Computer Science

Inheritance and Interfaces 2(49)

Page 3: forel2

GENERAL INFORMATION ABOUT INHERITANCE

Inheritance Department of Computer Science

Inheritance and Interfaces 3(49)

Page 4: forel2

Inheritance

◮ For a programming language to be object oriented it needs to

support inheritance.

◮ The main idea about inheritance is to reuse code instead of

rewriting it.

◮ With inheritance, it is possible for a class to contain all thepublic parts of another class.

◮ Field variables (attributes), methods and relations to other

classes.

◮ It is called an inheritance because the subclass is given all

the public parts of the superclass.

◮ It is a powerful, but also sometimes difficult, relationship

between two classes.

Inheritance Department of Computer Science

Inheritance and Interfaces 4(49)

Page 5: forel2

Inheritance in real life

◮ As with much of what is in object orientation, inheritance is

taken from the real world.

◮ Whenever a human is looking around, classifications aredone on the subjects seen.

◮ You see people, not individuals and so on.

◮ In the same way, humans tend to group similar subjects intohierarchical groups.

◮ Animals are seen as dogs, cats, cows and so on.◮ In the group dogs, there are several species of dogs.

◮ This can be called a taxonomy of animals.◮ Made famous by the 18th century scientist Carl Linnæus.

Inheritance Department of Computer Science

Inheritance and Interfaces 5(49)

Page 6: forel2

Linnean taxonomy

Figure: ”SN-p837”. Licensed under CC BY 2.5 via Wikimedia Commons- http://commons.wikimedia.org/wiki/File:SN-p837.jpg#

mediaviewer/File:SN-p837.jpg

Inheritance Department of Computer Science

Inheritance and Interfaces 6(49)

Page 7: forel2

Taxonomy of some birds. . .

Inheritance Department of Computer Science

Inheritance and Interfaces 7(49)

Page 8: forel2

Semantics of inheritance

◮ In object orientation the inheritance relation is called an is–arelation.

◮ A Cissa is–a Corvidae is–a Passeriformes is–a Aves is–aPhylum Chordata

◮ A Teacher is–an Employee◮ A Car is–a Vehicle

◮ Everything public in the superclass is inherited down to the

subclass.

◮ It is possible to create purely functional inheritance, but froma semantic point of view this is hard to understand.

◮ Also, it makes maintaining the code a lot harder.

Inheritance Department of Computer Science

Inheritance and Interfaces 8(49)

Page 9: forel2

Terminology

◮ Inheritance is also sometimes called generalisation.◮ This is because the superclasses are generalisations of the

subclasses.◮ This also implies that the subclasses are specialisations of the

superclass.

◮ In addition to being called super-/subclass, the classes canalso be called:

◮ Superclass: base class or parent◮ Subclass: child or descendent

◮ In Java, the terms “base class” and “subclass” are the most

common.

Inheritance Department of Computer Science

Inheritance and Interfaces 9(49)

Page 10: forel2

INHERITANCE IN JAVA

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 10(49)

Page 11: forel2

The base class

◮ The base class is constructed just as before:

StarShip

maker : String

model : String

StarShip ( )

setMaker ( makerName : String) )

getMaker ( ) : String

setModel ( modelName : String))

getModel ( ) : String

package inheritance;

public class StarShip {

private String maker;

private String model;

public StarShip() {

}

public void setMaker(String makerName) {

maker = makerName;

}

public String getMaker() {

return maker;

}

public void setModel(String modelName) {

model = modelName;

}

public String getModel() {

return model;

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 11(49)

Page 12: forel2

The subclass

◮ To make a class a subclass of another class, extends is added

after the class declaration.

StarShip

maker : String

model : String

StarShip ( )

setMaker ( makerName : String) )

getMaker ( ) : String

setModel ( modelName : String)

getModel ( ) : String

Fighter

noOfWeapons : Integer

Fighter ( )

setWeapons ( newWeapons : Integer) )

getWeapons ( ) : Integer

package inheritance;

public class Fighter extends StarShip {

private int noOfWeapons;

public Fighter() {

}

public void setWeapons(int newWeapons) {

noOfWeapons = newWeapons;

}

public int getWeapons() {

return noOfWeapons;

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 12(49)

Page 13: forel2

The object

◮ It is now possible to create an object containing all fields and

an methods from the base class plus those from the subclass.

xwing:Fighter

noOfWeapons = 6

maker = Incom Corporation

model = T-65 X-Wing

◮ In the object, the maker and model are from the base class

while the number of weapons is from the subclass.

◮ Notice that it is only the public parts that are inherited, so in

reality it is methods for getting and setting the base class’

members.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 13(49)

Page 14: forel2

Inheriting to several subclasses

◮ It is possible for one base class to inherit down to two or

more subclasses.StarShip

maker : String

model : String

StarShip ( )

setMaker ( makerName : String) )

getMaker ( ) : String

setModel ( modelName : String) )

getModel ( ) : String

Fighter

noOfWeapons : Integer

Fighter ( )

setWeapons ( newWeapons : Integer) )

getWeapons ( ) : Integer

Freighter

capacity : Integer

Freighter ( )

setCapacity ( newCapacity : Integer) )

getCapacity ( ) : Integer

◮ Notice, though, that it is not possible for a subclass to havetwo or more direct base classes.

◮ This will be addressed later in the lecture.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 14(49)

Page 15: forel2

Creating objects

◮ As it is now, it is possible to create objects from any of the

classes.

public static void main(String[] args) {

StarShip anonymous = new StarShip();

Fighter xwing = new Fighter();

anonymous.setMaker("Anonymous Ships Inc");

anonymous.setModel("Noname 2000");

xwing.setMaker("Incom Corporation");

xwing.setModel("T-65 X-wing starfighter ");

xwing.setWeapons(6);

}

◮ Notice that .setWeapons() is only available for the Fighter

object.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 15(49)

Page 16: forel2

Higher hierarchies

◮ There is no limit to the height of an inheritance from a

technical point of view.◮ To make the code manageable, it is often a good idea to limit

the height to about five.StarShip

maker : String

model : String

StarShip ( )

setMaker (makerName : String )

getMaker ( ) : String

setModel (modelName : String )

getModel ( ) : String

Fighter

noOfWeapons : Integer

Fighter ( )

setWeapons (newWeapons : Integer )

getWeapons ( ) : Integer

Freighter

capacity : Integer

Freighter ( )

setCapacity (newCapacity : Integer )

getCapacity ( ) : Integer

Configuration

noOfCrew : Integer

Configuration ( )

setCrew (newCrew : Integer )

getCrew ( ) : Integer

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 16(49)

Page 17: forel2

Constructors and inheritance

◮ Even if the constructor is declared to be public, it is notinherited to subclasses.

◮ As previously, any class not declaring a constructor will get

one default constructor.

◮ If constructors are explicitly declared, the default constructor

will be “removed”.

◮ After one or more constructors are added to the base class, it

is possible to call them from the subclasses.

◮ Calling the base class constructor is done using the super()

keyword with the correct parameters.◮ The base class can have several constructors and super()

needs to call the correct one.

◮ Notice that it is also possible set values by calling the getters

and setters of the base class manually.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 17(49)

Page 18: forel2

Extended classes

public class StarShip {

private String maker;

private String model;

public StarShip() {

}

public StarShip(String mk, String md){

maker = mk;

model = md;

}

public void setMaker(String makerName) {

maker = makerName;

}

public String getMaker() {

return maker;

}

public void setModel(String modelName) {

model = modelName;

}

public String getModel() {

return model;

}

}

public class Fighter extends StarShip {

private int noOfWeapons;

public Fighter() {

}

public Fighter(String mk, String md, int wps) {

super(mk, md);

noOfWeapons = wps;

}

public void setWeapons(int newWeapons) {

noOfWeapons = newWeapons;

}

public int getWeapons() {

return noOfWeapons;

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 18(49)

Page 19: forel2

More on constructors

◮ When instantiating the object, it is possible to use the

constructor that initialises both parts of the object:

Fighter bwing = new Fighter("Slayn & Korpil",

"A/SF-01 B-wing heavy fast attack starfighter", 5);

◮ Using the object is the same as before:

System.out.println("The B-wing is made by " + bwing.getMaker());

◮ One thing to notice about super() is that it only works for the

direct base class, there is no such thing as super().super().

◮ super can also be used to call another method in the base

class:

super.getDateCreated(); // fictive method

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 19(49)

Page 20: forel2

Overriding methods

◮ Methods are inherited from base classes to subclasses.◮ This applies public methods – if a method is private it is

only reachable from the same class.

◮ The idea of overriding a method is that a subclass might like

to either redefine or modify a method from a base class.

◮ To to this, the exact same method signature is used in thesubclass.

◮ If the subclass wants to modify the behaviour or the base

class, the super() keyword can be used.◮ Otherwise the subclass can just reimplement the behaviour.

◮ Notice that only instance methods can be overridden, not

static methods.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 20(49)

Page 21: forel2

Example

◮ In this example two classes

are created.

◮ Both classes has a method

called makeSound() that

returns the sound of an

animal.

◮ The string is began in the

base class and added to in

the subclass.

◮ By using super we first

execute the base class

method and then add the

subclass string.

Animal

name : String

Animal ( )

setName (aName : String )

getName ( ) : String

makeSound ( ) : String

Rancor

subspecies : String

Rancor ( )

setSubspecies (aSpecies : String)

getSubspecies ( ) :String

makeSound ( ) :String

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 21(49)

Page 22: forel2

Example

◮ Base class to the left and the subclass to the right.

public class Animal {

String name;

public Animal() {

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String makeSound() {

return name + " makes a ";

}

}

public class Rancor extends Animal {

String subspecies;

public Rancor() {

}

public String getSubspecies() {

return subspecies;

}

public void setSubspecies(String subspecies) {

this.subspecies = subspecies;

}

public String makeSound() {

return super.makeSound() +

" terrifying \"Aaaarrggh!\"";

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 22(49)

Page 23: forel2

Using the classes

◮ Instantiating and using the classes is the same as before:Rancor rancor = new Rancor();

rancor.name = "Jabba\’s rancor";

rancor.subspecies = "Tyrant rancor";

System.out.println(rancor.makeSound());

◮ The above will output the following:

Jabba's rancor makes a terrifying "Aaaarrggh!"

◮ Remember from last course that a method also can be

overloaded.

◮ If several overloaded methods exist, each has to be

overridden in the subclasses (if needed).

◮ Lastly, from Java 7 and onwards it is possible to add the

annotation @Override before a method that overrides a base

class method.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 23(49)

Page 24: forel2

Abstract classes

◮ There are times when it is not a good thing to be able tocreate an object from a class.

◮ In the previous examples there might only exist Rancors, but

not pure Animals.

◮ In that case, it is advisable to create an abstract class.

◮ An abstract class tells about what is important in subclasses.

◮ It is possible to create both concrete and abstract methods inabstract classes.

◮ An abstract method does not have an implementation at all,just a signature.

◮ Concrete methods can only be called from concrete

subclasses.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 24(49)

Page 25: forel2

Example class diagram

«Java Class»

NonSentient

diet : String

NonSentient()

NonSentient(String, String,String)

getDiet() : String

setDiet(String) :void

showInfo() : String

«Java Class»

Humanoid

nearHuman : boolean

Humanoid()

Humanoid(String, String,String,boolean)

isNearHuman() : boolean

setNearHuman(boolean) :void

showInfo() : String

«Java Class»

NonHumanoid

arms : int

legs : int

NonHumanoid()

NonHumanoid(String, String, String,int,int)

getArms() : int

setArms(int) : void

getLegs() : int

setLegs(int) :void

showInfo() : String

«Java Class»

Species

name : String

description : String

Species()

Species(String,String)

getName() : String

setName(String) :void

getDescription() : String

setDescription(String) :void

showInfo() : String

«Java Class»

Sentient

language : String

Sentient()

Sentient(String, String,String)

getLanguage() : String

setLanguage(String) :void

showInfo() : String

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 25(49)

Page 26: forel2

Base class, abstract class

public abstract class Species {

private String name;

private String description;

public Species(){}

public Species(String n, String d){

name = n;

description = d;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

public abstract String showInfo();

}

«Java Class»

Species

name : String

description : String

Species()

Species(String,String)

getName() : String

setName(String) :void

getDescription() : String

setDescription(String) :void

showInfo() : String

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 26(49)

Page 27: forel2

Sentient and NonSentient classes

public class Sentient extends Species {

private String language;

public Sentient() {

}

public Sentient(String n, String d, String l){

super(n, d);

language = l;

}

public String getLanguage() {

return language;

}

public void setLanguage(String language) {

this.language = language;

}

@Override

public String showInfo() {

return "A " + this.getName() +

" speaks " + language;

}

}

public class NonSentient extends Species {

private String diet;

public NonSentient() {

}

public NonSentient(String n, String d, String dt){

super(n, d);

diet = dt;

}

public String getDiet() {

return diet;

}

public void setDiet(String diet) {

this.diet = diet;

}

@Override

public String showInfo() {

return "A " + this.getName() +

" eats " + diet;

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 27(49)

Page 28: forel2

Humanoid classpublic class Humanoid extends Sentient {

private boolean nearHuman;

public Humanoid() {

}

public Humanoid(String n, String d, String l, boolean nh) {

super(n, d, l);

nearHuman = nh;

}

public boolean isNearHuman() {

return nearHuman;

}

public void setNearHuman(boolean nearHuman) {

this.nearHuman = nearHuman;

}

@Override

public String showInfo(){

if(nearHuman)

return super.showInfo() + " and is a near human. ";

else

return super.showInfo() + " and is not a near human.";

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 28(49)

Page 29: forel2

NonHumanoid classpublic class NonHumanoid extends Sentient {

private int arms;

private int legs;

public NonHumanoid() {}

public NonHumanoid(String n, String d, String l, int a, int lgs) {

super(n, d, l);

arms = a;

legs = lgs;

}

public int getArms() {

return arms;

}

public void setArms(int arms) {

this.arms = arms;

}

public int getLegs() {

return legs;

}

public void setLegs(int legs) {

this.legs = legs;

}

@Override

public String showInfo(){

return super.showInfo() + " and has " + arms + " arms and " + legs + " legs.";

}

}

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 29(49)

Page 30: forel2

Usage

◮ All concrete classes can be instantiated but not the abstract

base class.

Humanoid tiin = new Humanoid("Saesee Tiin", "Saesee Tiin was a --- CUT --- Clone

System.out.println(tiin.showInfo());

System.out.println(tiin.getDescription());

NonHumanoid jabba = new NonHumanoid("Jabba Desilijic Tiure", "Jabba Desilijic Tiure,

--- CUT --- Syndicate. ", "Huttese", 2, 1);

System.out.println(jabba.showInfo());

◮ Output will be:A Saesee Tiin speaks Basic and is a near human.

Saesee Tiin was a male Iktotchi Jedi Master and a member of the Jedi High Council

in the last days of the Galactic Republic. Having apprenticed under the esteemed

Jedi Master Omo Bouri, Tiin rarely spoke and kept to himself. Never choosing to

take a Padawan himself, Tiin took the rank of Jedi General in the Grand Army of

the Republic during the Clone Wars.

A Jabba Desilijic Tiure speaks Huttesee and has 2 arms and 1 legs.

Inheritance in Java Department of Computer Science

Inheritance and Interfaces 30(49)

Page 31: forel2

POLYMORPHISM

Polymorphism Department of Computer Science

Inheritance and Interfaces 31(49)

Page 32: forel2

Polymorphism

◮ Object orientation rests on three pillars; encapsulation,

inheritance and polymorphism.

◮ The previous course talked about encapsulation and this

lecture has dealt with inheritance.

◮ This part will be about polymorphism.

◮ The word polymorphism comes form Greek and means

“many forms”.

◮ In an inheritance relation a subclass inherits all the features

of the base class and adds more.

◮ As each subclass is a specification of its base class, it is its

base class.

◮ This is the foundation of polymorphism.

Polymorphism Department of Computer Science

Inheritance and Interfaces 32(49)

Page 33: forel2

Understanding substitution

◮ Consider the inheritance to the

right again.

◮ In this structure, a Fighter is-a

StarShip.

◮ Everywhere a StarShip is

expected, a Fighter can be used

as it is of its base class.

◮ Notice that it doesn’t work theother way around!

◮ While every Fighter is aStarShip, not every StarShip is

a Fighter.

StarShip

maker : String

model : String

StarShip ( )

setMaker ( makerName : String) )

getMaker ( ) : String

setModel ( modelName : String)

getModel ( ) : String

Fighter

noOfWeapons : Integer

Fighter ( )

setWeapons ( newWeapons : Integer) )

getWeapons ( ) : Integer

Polymorphism Department of Computer Science

Inheritance and Interfaces 33(49)

Page 34: forel2

Dynamic method lookup

◮ The substitution means that at compile time only the type of

the object is checked.

◮ Polymorphism then means that it is possible to determine the

method to run at runtime.

◮ The method that is executed is the one for the actual object

used at the moment.

◮ This process is also called late binding or dynamic binding.◮ The book uses the phrase “method lookup” but it means the

same.

◮ Polymorphism therefore makes it relatively easy to extend

programs as we need only to add new classes with new

behaviour.

Polymorphism Department of Computer Science

Inheritance and Interfaces 34(49)

Page 35: forel2

Example

public class Superhero {

private String name;

public Superhero() {

}

public Superhero(String n){

name = n;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String action(){

return "I am going to ";

}

}

Polymorphism Department of Computer Science

Inheritance and Interfaces 35(49)

Page 36: forel2

Subclasses

public class Natural extends Superhero {

private String advantage;

public Natural() {

}

public Natural(String n, String a){

super(n);

advantage = a;

}

public String getAdvantage() {

return advantage;

}

public void setAdvantage(String advantage) {

this.advantage = advantage;

}

@Override

public String action() {

return super.action() + "use my " +

advantage + " to rescue you!";

}

}

public class Supernatural extends Superhero {

private String power;

public Supernatural() {

}

public Supernatural(String n, String p) {

super(n);

power = p;

}

public String getPower() {

return power;

}

public void setPower(String power) {

this.power = power;

}

@Override

public String action() {

return super.action() + "use " +

power + " to rescue you!";

}

}

Polymorphism Department of Computer Science

Inheritance and Interfaces 36(49)

Page 37: forel2

Example use

◮ The following code shows how the actual binding is done at

runtime and not compile time.ArrayList<Superhero> theHeroes = new ArrayList<>();

theHeroes.add(new Natural("Batman", "advanced technology"));

theHeroes.add(new Supernatural("Cyclops", "optic force blasts"));

theHeroes.add(new Natural("Iron Man", "supreme technology"));

theHeroes.add(new Supernatural("Mister Fantastic", "shapeshifting"));

theHeroes.add(new Natural("Hawkeye", "grandmaster archery"));

theHeroes.add(new Supernatural("Wolverine", "adamantium claws"));

for(Superhero sh: theHeroes)

System.out.println(sh.action());

◮ Output:I am going to use my advanced technology to rescue you!

I am going to use optic force blasts to rescue you!

I am going to use my supreme technology to rescue you!

I am going to use shapeshifting to rescue you!

I am going to use my grandmaster archery to rescue you!

I am going to use adamantium claws to rescue you!

Polymorphism Department of Computer Science

Inheritance and Interfaces 37(49)

Page 38: forel2

INTERFACES

Interfaces Department of Computer Science

Inheritance and Interfaces 38(49)

Page 39: forel2

The reason for interfaces

◮ Inheritance is, as discussed previously, only

possible from one base class.

◮ Some languages, like C++ and Scala (using

mixin classes), allow for multiple

inheritance.

◮ The problem is called “The diamond

problem” and refers to the ambiguity that

arises if class B and C inherit from A and D

inherits from both B and C.

◮ If there is a method in class B and C that is

not overridden in D, which of them should

D execute?

A

aMethod ( )

B

aMethod ( )

C

aMethod ( )

D

aMethod ( )

Interfaces Department of Computer Science

Inheritance and Interfaces 39(49)

Page 40: forel2

Interfaces

◮ The idea of interfaces is to define the desired behaviour of a

class.

◮ An interface is a contract between two classes.◮ A contract of what services a class should have.

◮ In order to do this, an interface has no implementation, only

method signatures.

◮ An interface is inherited to another class which then must

implement the methods.

◮ As no implementation is given in an interface, a class can

inherit – or implement – several interfaces at once.

Interfaces Department of Computer Science

Inheritance and Interfaces 40(49)

Page 41: forel2

Usage scenarios for interfaces

◮ Interfaces are used extensively in the collection classes, the

different algorithms for (among other things) searching and

sorting lists.

◮ The idea is that the interface defines that a data structure issortable and different classes can implement that differently.

◮ Later in the course several ways of implementing sorting will

be discussed.◮ Different algorithms have different characteristics for different

data structures.

◮ Another use is the compareTo() method of the Comparable

interface.◮ It is easy to understand how two integers are compared, but

how do you compare two StarShips?

Interfaces Department of Computer Science

Inheritance and Interfaces 41(49)

Page 42: forel2

Using Comparable

◮ The interface Comparable contains one method called

compareTo():

public interface Comparable

{

int compareTo(Object o);

}

◮ This also illustrates how interfaces are declared, usinginterface instead of class.

◮ Also notice that all methods must end with a semicolon, noimplementation.

◮ A class can then implement this interface as shown on the

next slide where Fighter implements it.

Interfaces Department of Computer Science

Inheritance and Interfaces 42(49)

Page 43: forel2

Implementing an interfacepublic class Fighter extends StarShip implements Comparable {

private int noOfWeapons;

public Fighter() {}

public Fighter(String mk, String md, int wps) {

super(mk, md);

noOfWeapons = wps;

}

public void setWeapons(int newWeapons) {

noOfWeapons = newWeapons;

}

public int getWeapons() {

return noOfWeapons;

}

@Override

public int compareTo(Object o) {

Fighter other = (Fighter) o;

if(noOfWeapons < other.noOfWeapons)

return -1;

if(noOfWeapons > other.noOfWeapons)

return 1;

return 0;

}

}

Interfaces Department of Computer Science

Inheritance and Interfaces 43(49)

Page 44: forel2

Using the classes

◮ The following code shows how the interface makes it

possible to sort an array of Fighters.Fighter xwing = new Fighter("Incom Corporation", "T-65 X-wing starfighter", 6);

Fighter bwing = new Fighter("Slayn & Korpil", "A/SF-01 B-wing heavy fast attack starfighter", 5);

Fighter awing = new Fighter("Alliance Underground Engineering", "RZ-1 A-wing interceptor", 3);

Fighter[] ships = new Fighter[3];

ships[0] = awing;

ships[1] = xwing;

ships[2] = bwing;

Arrays.sort(ships);

for(Fighter f: ships)

System.out.println(f.getModel());

◮ Output will be:RZ-1 A-wing interceptor

A/SF-01 B-wing heavy fast attack starfighter

T-65 X-wing starfighter

Interfaces Department of Computer Science

Inheritance and Interfaces 44(49)

Page 45: forel2

Creating an interface

◮ As seen before, only the keyword interface and the lack ofimplementation differs from a class.

◮ Also notice that any field variables also count as

implementation, so they are not allowed either.

◮ In the following example an interface called Edible is added

to the previous NonSentient class.

public interface Edible {

public String howToEat();

public String recipe(int number);

}

◮ The next slide will show most of the modified class.

Interfaces Department of Computer Science

Inheritance and Interfaces 45(49)

Page 46: forel2

New NonSentient

public class NonSentient extends Species implements Edible {

private String diet;

private String eat;

private String cooking;

public NonSentient() {

}

public NonSentient(String n, String d, String dt, String e, String c) {

super(n, d);

diet = dt;

eat = e;

cooking = c;

}

// Cut for space

@Override

public String howToEat() {

return eat;

}

@Override

public String recipe(int number) {

return "For " + number + " portions of " + this.getName() + " do the following:\n" + cooking;

}

}

Interfaces Department of Computer Science

Inheritance and Interfaces 46(49)

Page 47: forel2

Using the class

◮ It is then possible to use it as previously seen.

NonSentient tauntaun = new NonSentient("Tauntaun",

"Smelly omnivorous reptomammal",

"anything", "barbecued",

"Use a large grill and barbecue it for several hours.");

System.out.println("A " + tauntaun.getName() + " is best served " +

tauntaun.howToEat());

System.out.println(tauntaun.recipe(4));

◮ The output of this will be:A Tauntaun is best served barbecued

For 4 portions of Tauntaun do the following:

Use a large grill and barbecue it for several hours.

◮ It is possible to add more interfaces to one class, for instanceit is possible to implement Comparable for NonSentient too.

◮ But what would it mean?

Interfaces Department of Computer Science

Inheritance and Interfaces 47(49)

Page 48: forel2

Default methods

◮ From Java 8 (not covered by the book) default methods have

been added to interfaces.

◮ With this, it is possible to add a default implementation to amethod in an interface.

◮ Thereby breaking the rule of no implementation in an

interface!

◮ This was done, mainly, to be able to add functionality to theexisting collection classes.

◮ In Java 8 functional programming with lambda expressions

was added and to be able to enhance the collection classes,

default methods were added.

◮ In most cases, you can ignore default methods, but it is good

to know about them.

Interfaces Department of Computer Science

Inheritance and Interfaces 48(49)

Page 49: forel2

Read the book!

◮ Chapter 9 in the book covers all that has been said (minus

default methods) and more.

◮ Make certain that you read the book to understand about:◮ Final classes◮ Protected access◮ Overriding toString() and equals() methods◮ instanceOf operator◮ The Object class

◮ All the parts discussed in this lecture are wildly used in Java

so make sure you know them.

Interfaces Department of Computer Science

Inheritance and Interfaces 49(49)