0% found this document useful (0 votes)
4 views46 pages

Lecture Slide

This document is a lecture on Object-Oriented Programming, focusing on abstract classes and interfaces. It explains the definitions, uses, and syntax of abstract classes and interfaces in Java, highlighting their differences and the necessity for method implementation in subclasses. The lecture also includes examples and UML representations to illustrate the concepts discussed.

Uploaded by

Vo Danh Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views46 pages

Lecture Slide

This document is a lecture on Object-Oriented Programming, focusing on abstract classes and interfaces. It explains the definitions, uses, and syntax of abstract classes and interfaces in Java, highlighting their differences and the necessity for method implementation in subclasses. The lecture also includes examples and UML representations to illustrate the concepts discussed.

Uploaded by

Vo Danh Hacker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

INFO1113 / COMP9003

Object-Oriented Programming

Lecture 6

The University of Sydney Page 1


Contents developed by Tyson Thomas
Acknowledgement of Country

I would like to acknowledge the Traditional Owners of Australia and recognise


their continuing connection to land, water and culture. I am currently on the land
of the Gadigal people of the Eora nation and pay my respects to their Elders,
past, present and emerging.

I further acknowledge the Traditional Owners of the country on which you are on
and pay respects to their Elders, past, present and future.

The University of Sydney Page 3


Copyright Warning

COMMONWEALTH OF AUSTRALIA
Copyright Regulations 1969
WARNING
This material has been reproduced and communicated to you by or on behalf of the
University of Sydney pursuant to Part VB of the Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright under the Act. Any
further copying or communication of this material by you may be the subject of
copyright protection under the Act.
Do not remove this notice.

The University of Sydney Page 4


Topics: Part A

● Abstract Classes

● Abstract Classes UML

The University of Sydney Page 5


What is an abstract class?

abstract là Animal

có đủ thuộc tính và phương thức Animal a = new Animal(); X


Although similar to a concrete class, an abstract class cannot be instantiated.
It can define methods and attributes which can be inherited, inherit from
super types and can be inherited from.

However, abstract classes can also enforce a method implementation for


subtypes. public abstract int display(); abstract class Base{
abstract method
public abstract int display();
}
class Subclass extends Base{ sum -> nhan vao 2 so a,b tra ve tong
// must implement display(): int cua chung
} sum(int a, int b){
return a+b;
Refer to Chapter 8.4, pages 684-688, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)
}
The University of Sydney Page 6
sum(1,2) -> 3
Why would we use abstract? sum(3,4) -> 7

sum(){ System.out.println(sum());
return 1+1;
}
The main case for abstract is that we have some type that we do not want
instantiated but is a generalisation of many other types.

Example:
● Shape is a generalisation of Triangle, Square, Circle but we don’t have a
concrete instance of Shape new Shape(); XXX

● Furniture is a generalisation of Chair, Sofa, Table and Desk. new Furniture(); XXX

Refer to Chapter 8.4, pages 684-688, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 7


Sounds like abstract classes are quite different from classes!

The University of Sydney Page 8


What can we still do?

We still are able to specify:

● Constructors
● Define methods (static and instance)
● Attributes
● Use all the access modifiers
● … everything a regular class can do except!

We cannot instantiate the class but we can specify methods subtypes must
define. Dog speak(); gau gau concrete class
Cat speak(); meo meo

AbstractClass a = new AbstractClass();

The University of Sydney Page 9


Declaration of an abstract class

Simply we are able to define an abstract class by using the abstract keyword.
This immediately marks the class as abstract and we do not need anything
more.

Syntax:
[modifier] abstract class ClassName

Example:
public abstract class Furniture

The University of Sydney Page 10


What if we try to instantiate it?

Since it is marked as abstract, the compiler will refuse to allow this type of
Animal Dog
instantiation.
breathe() breathe()
Concrete Class {
Abstract Class speak() // your implementation
}
eat()

> javac FurnitureStore.java


FurnitureStore.java:22: error: Furniture is abstract; cannot be instantiated
Furniture f = new Furniture("Table");
^
1 error
<program end>

The University of Sydney Page 11


breathe
Abstract methods eat
Animal
speak

how it does Dog, Lion, Tiger,....


We are able to declare an abstract method in only abstract classes. When we
declare an abstract method we do not define a method body (the logic of the
method).

public abstract void stack(Furniture f);


abstract method thi k co method body

The class should not be instantiated and behaviour is defined by the subtypes
and not the super type. inheritance

The University of Sydney Page 12


Declaration of an abstract class

We have an abstract class specified.


import java.util.List;
import java.util.ArrayList;

public abstract class Furniture {

private String name;


private List<Part> parts;

public Furniture(String name) {


this.name = name;
this.parts = new ArrayList<Part>();
}

public void addPart(Part p) {


parts.add(p);
}

public abstract void stack(Furniture f);


}

Notice we have declared


an abstract method.

The University of Sydney Page 13


Declaration of an abstract class

We have an abstract class specified.


import java.util.List;
import java.util.ArrayList; public class Chair extends Furniture {

public abstract class Furniture { public Chair() {


super("Chair");
private String name;
}
private List<Part> parts;

public Furniture(String name) { }


this.name = name;
this.parts = new ArrayList<Part>();
}

public void addPart(Part p) {


parts.add(p);
}

public abstract void stack(Furniture f);


} > javac FurnitureStore.java
Chair.java:1: error: Chair is not abstract and does not override abstract
public class FurnitureStore {
method stack(Furniture) in Furniture
public static void main(String[] args) {
public class Chair extends Furniture {
Chair ch = new Chair();
^
ch.stack(new Chair());
} 1 error
}
The University of Sydney Page 14
Declaration of an abstract class

We have an abstract class specified.


import java.util.List;
import java.util.ArrayList; public class Chair extends Furniture {

public abstract class Furniture { public Chair() {


super("Chair");
private String name;
}
private List<Part> parts;

public Furniture(String name) {


this.name = name;
public void stack(Furniture f) {
this.parts = new ArrayList<Part>(); System.out.println(“Don’t put furniture on chairs!");
} }
}
public void addPart(Part p) {
parts.add(p); Now we have defined the
} method stack in the
subclass.
public abstract void stack(Furniture f);
}
> javac FurnitureStore.java
public class FurnitureStore { >
public static void main(String[] args) {
Chair ch = new Chair();
ch.stack(new Chair());
}
}
The University of Sydney Page 15
Declaration of an abstract class

We have an abstract class specified.


import java.util.List;
import java.util.ArrayList; public class Chair extends Furniture {

public abstract class Furniture { public Chair() {


super("Chair");
private String name;
}
private List<Part> parts;

public Furniture(String name) {


this.name = name;
public void stack(Furniture f) {
this.parts = new ArrayList<Part>(); System.out.println(“Don’t put furniture on chairs!");
} }
}
public void addPart(Part p) {
parts.add(p); Now we have defined the
} method stack in the
subclass.
public abstract void stack(Furniture f);
}
> java FurnitureStore
public class FurnitureStore { Don’t put furniture on chairs!
public static void main(String[] args) {
Chair ch = new Chair();
ch.stack(new Chair());
} We can now declare and invoke
} stack through Chair class.
The University of Sydney Page 16
Demonstration

The University of Sydney Page 17


Abstract Classes and UML abstract class vs concrete class

Within a UML class diagram, we can illustrate abstract classes with the
following.

Italicised font shows that it


is an abstract class.

We also show polymorphic


method as italicised.

The University of Sydney Page 18


Let’s take a break!

The University of Sydney Page 19


Topics: Part B

● Interfaces

● Interfaces and UML

● Default Method in Interfaces

The University of Sydney Page 20


Interfaces public class SubClass extends SuperClass
D(); A();
extends B();
We will be introducing a new keyword implements. C();

lop con extends lop cha


Interfaces share a similarity with Abstract Classes in that they declare
methods that a subclass must implement and they cannot be instantiated.
However, unlike classes, they can be implemented by classes as many times
as they like.
java allows extend only one class
class A implements Ia,Ib,Ic,...
We are not bound to implementing a single interface, we can implement
multiple interfaces.

new, this, extends, super, implements

Refer to Chapter 8.4, pages 659-669, (Java, An Introduction to Problem Solving & Programming, Savitch & Mock)

The University of Sydney Page 21


class A {
Interfaces //attributes
private boolean check;
//methods
private void hello(){};
Interfaces }
● Cannot specify any attributes only methods khác với Abstract class
● Do not (typically) provide a method definition
● Cannot instantiate them interface B {
//abstract methods
● Can be implemented multiple times private abstract void hello();
}

From an application design perspective we need to consider how we can use


interfaces and where they are appropriate. abstract class C {
//attributes
private int number;
//methods
private void hello() {};

// abstract methods
private abstract void test();
The University of Sydney } Page 22
Declaration of an interfaces

Simply we are able to define an interface by using the interface keyword.

Syntax:
[modifier] interface InterfaceName

Example:

public interface Swim


public abstract class AClass

The University of Sydney Page 23


Declaration of an interfaces

Simply we are able to define an interface by using the interface keyword.

Syntax:
[modifier] interface InterfaceName

To be clear, an interface is
Example: not a class.

public interface Swim {


public void floating();
public void diving();
}

The University of Sydney Page 24


Declaration of an interfaces

Simply we are able to define an interface by using the interface keyword.

Syntax:
[modifier] interface InterfaceName

Example:

public interface Swim {


public void floating();
To be clear, an interface is public void diving();
not a class. It defines a
group a methods for }
implementers to define.

The University of Sydney Page 25


Declaration of an interfaces

Simply we are able to define an interface by using the interface keyword.

Syntax:
[modifier] interface InterfaceName

public class YourClassName [extends ...] [implements ...,...,...]


Example:

Since a Dog class


public interface Swim { implements the Swim
interface it will need to
public void floating(); define the methods for
Swim.
To be clear, an interface is public void diving();
not a class. It defines a
group a methods for }
implementers to define.
public class Dog implements Swim

The University of Sydney Page 26


Interfaces
So let’s take a look at the following example
Interface declares methods that public interface Move {
must be implemented by public void move(double hours);
subclass }

public class Dog implements Move {


define = implement public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; private double kmTravelled = 0.0;

public Dog(String region) { public Dolphin(String region) {


this.region = region; this.region = region;
} }
override override
public void move(double hours) { public void move(double hours) {
if(region.equals("water")) if(region.equals("water"))
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
else if(region.equals("land")) else if(region.equals("land")) {
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} }

public double getKMTravelled() { public double getKMTravelled() {


return kmTravelled; return kmTravelled;
} }
} }

The University of Sydney Page 27


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; private double kmTravelled = 0.0;

public Dog(String region) { public Dolphin(String region) {


this.region = region; this.region = region;
} }

public void move(double hours) { public void move(double hours) {


if(region.equals("water")) if(region.equals("water"))
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
else if(region.equals("land")) else if(region.equals("land")) {
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} }

public double getKMTravelled() { public double getKMTravelled() {


return kmTravelled; return kmTravelled;
} }
} }

The University of Sydney Page 28


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; private double kmTravelled = 0.0;

public Dog(String region) { public Dolphin(String region) {


this.region = region; this.region = region;
} }

public void move(double hours) { public void move(double hours) {


if(region.equals("water")) if(region.equals("water"))
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
else if(region.equals("land")) else if(region.equals("land")) {
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} }

public double getKMTravelled() { They both have a similar implementation but


public double getKMTravelled() {
return kmTravelled; their land and water movementreturn
speed is
kmTravelled;
} different. We could change it }completely
} between the two implementations.
}

The University of Sydney Page 29


Interfaces
So let’s take a look at the following example
We have defined our
Move dog = new Dog(); public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
Move dop = new Dolphin(); } and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public void move(double hours) { public void move(double hours) {


if(region.equals("water")) if(region.equals("water"))
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
else if(region.equals("land")) else if(region.equals("land")) {
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} }

public double getKMTravelled() { They both have a similar implementation but


public double getKMTravelled() {
return kmTravelled; their land and water movementreturn
speed is
kmTravelled;
} different. We could change it }completely
} between the two implementations.
}

The University of Sydney Page 30


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public classpublic
MovingAnimals {
void move(double hours) {
interface is not a class public void move(double hours) {
public static void main(String[] args) { if(region.equals("water"))
if(region.equals("water"))
Dog dog = new Dog("land");
kmTravelled += (waterSpeed_kmh *hours); We cankmTravelled
create an Move[]
+= (waterSpeed_kmh * hours);
Dolphin dolphin = new Dolphin("land");
else if(region.equals("land")) array else
andif(region.equals("land"))
add both dog {
Move[] movingAnimals = {dog, dolphin};
kmTravelled += (landSpeed_kmh * hours); and dolphin types+=to(landSpeed_kmh
kmTravelled it. * hours);
} m : movingAnimals) {
for(Move Why?}
m.move(1.0);
} public double getKMTravelled() { They both have a similar implementation but
public double getKMTravelled() {
return kmTravelled; their land and water movementreturn
speed is
kmTravelled;
System.out.println(dog.getKMTravelled());
} different. We could change it }completely
System.out.println(dolphin.getKMTravelled());
} between the two implementations.
}
}
}

The University of Sydney Page 31


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public classpublic
MovingAnimals {
void move(double hours) { public void move(double hours) {
public static void main(String[] args) { if(region.equals("water"))
if(region.equals("water"))
Dog dog = new Dog("land");
kmTravelled += (waterSpeed_kmh *hours); We cankmTravelled
create an Move[]
+= (waterSpeed_kmh * hours);
Dolphin dolphin = new Dolphin("land");
else if(region.equals("land")) array else
andif(region.equals("land"))
add both dog {
Move[] movingAnimals = {dog, dolphin};
kmTravelled += (landSpeed_kmh * hours); and dolphin types+=to(landSpeed_kmh
kmTravelled it. * hours);
} m : movingAnimals) {
for(Move Why?}
m.move(1.0); Because they are of type
} public double getKMTravelled() { Move.
They both have a similar implementation but
public double getKMTravelled() {
return kmTravelled; their land and water movementreturn
speed is
kmTravelled;
System.out.println(dog.getKMTravelled());
} different. We could change it }completely
System.out.println(dolphin.getKMTravelled());
} between the two implementations.
}
}
}

The University of Sydney Page 32


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public classpublic
MovingAnimals {
void move(double hours) { public void move(double hours) {
public static void main(String[] args) { if(region.equals("water"))
if(region.equals("water"))
Dog dog = new Dog("land"); If they of type Move we
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
Dolphin dolphin = new Dolphin("land"); are guaranteed to be able
else if(region.equals("land")) else if(region.equals("land")) {
Move[] movingAnimals = {dog, dolphin}; to use move() method.
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} m : movingAnimals) {
for(Move }
m.move(1.0);
} public double getKMTravelled() { They both have a similar implementation but
public double getKMTravelled() {
return kmTravelled; their land and water movementreturn
speed is
kmTravelled;
System.out.println(dog.getKMTravelled());
} different. We could change it }completely
System.out.println(dolphin.getKMTravelled());
} between the two implementations.
}
}
}

The University of Sydney Page 33


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public classpublic
MovingAnimals {
void move(double hours) { public void move(double hours) {
public static void main(String[] args) { if(region.equals("water"))
if(region.equals("water"))
Dog dog = new Dog("land");
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
Dolphin dolphin = new Dolphin("land");
else if(region.equals("land")) else if(region.equals("land")) {
Move[] movingAnimals = {dog, dolphin};
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} m : movingAnimals) {
for(Move }
m.move(1.0);
} public double getKMTravelled() { They both have a similar implementation but
public double getKMTravelled() {
We can
their land and water movement see
speed the
is updated
return kmTravelled;
return kmTravelled;
System.out.println(dog.getKMTravelled()); different. We could changevariables that have been
it }completely
}
System.out.println(dolphin.getKMTravelled()); applied to both objects.
between the two implementations.
} }
}
}

The University of Sydney Page 34


Interfaces
So let’s take a look at the following example
We have defined our
public interface Move { Interface Move that will
public void move(double hours); be implemented by Dog
} and Dolphin.

public class Dog implements Move { public class Dolphin implements Move {
private String region; //Water or Land private String region; //Water or Land
private double landSpeed_kmh = 50.0; private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 8.0; Since they both private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0; implement Move private double kmTravelled = 0.0;
interface, we can treat
public Dog(String region) { them as a Move type. public Dolphin(String region) {
this.region = region; this.region = region;
} }

public classpublic
MovingAnimals {
void move(double hours) { public void move(double hours) {
public static void main(String[] args) { if(region.equals("water"))
if(region.equals("water"))
Dog dog = new Dog("land");
kmTravelled += (waterSpeed_kmh *hours); kmTravelled += (waterSpeed_kmh * hours);
Dolphin dolphin = new Dolphin("land");
else if(region.equals("land"))
Move[] movingAnimals = {dog, dolphin};
> java MovingAnimals
else if(region.equals("land")) {
kmTravelled += (landSpeed_kmh * hours); kmTravelled += (landSpeed_kmh * hours);
} m : movingAnimals) {
for(Move
50.0 }
m.move(1.0); 1.0
They both have a similar implementation but We
public double getKMTravelled() {
can then see that
} public double getKMTravelled() {
their land and<program
water movement speed is move() has changed an
return kmTravelled;
System.out.println(dog.getKMTravelled());
end>
return kmTravelled;
different. We could change it }completely internal travelled variable.
}
System.out.println(dolphin.getKMTravelled());
} between the two implementations.
}
}
}

The University of Sydney Page 35


Using interfaces!

The University of Sydney Page 36


Note: Interfaces

Okay, I lied a little, we can have attributes in an interface.

However! The attributes are: static , final -> by default


● Static (They belong to the interface)
● Constant (have the final modifier applied to them)

Therefore we cannot use them for instances.

The University of Sydney Page 37


Interface and UML

Just like abstract classes we can represent an interface within UML however it
is slightly different than others. ClassName
Attribute
We specify the stereotype
Methods
in UML to be interface and
this gives us specificity of
language constructs.

Italicised font shows that it


is a polymorphic method

The University of Sydney Page 38


Interface and UML

Just like abstract classes we can represent an interface within UML however it
is slightly different than others.
However! The relationship link is different than that of a classes.

implements

extends

The University of Sydney Page 39


Interface and UML

Just like abstract classes we can represent an interface within UML however it
is slightly different than others.
However! The relationship link is different than that of a classes.

The University of Sydney Page 40


Interface and UML

Just like abstract classes we can represent an interface within UML however it
is slightly different than others.
However! The relationship link is different than that of a classes.

This is a realization link


between an implementer
and the interface.

The University of Sydney Page 41


Default Method

We know interfaces and now we will be visiting default methods with


java and their utility. This is a new feature in Java that allows methods to
be defined in an interface.

Prior to Java 8, interfaces just specified the method declaration and


never a default method.

The University of Sydney Page 42


Syntax of a default method

Simply we are able to define a default method by using the default keyword.

Syntax:
[modifier] default <returntype> MethodName([parameters])

Example:

private default void swim();

The University of Sydney Page 43


Default Method

interface Talk {
public void talk();
public default void talking(){
System.out.println(“I am talking.”);
}
}

public class Alien implements Talk { public class Cat implements Talk {

public void talk() { public void talk() {


System.out.println(“zzzfer342aa”); System.out.println(“meow”);
} }
} }

Both Alien and Cat implement the talk


behaviour through the interface.

The University of Sydney Page 44


Default Method

interface Talk {
public void talk();
public default void talking(){
System.out.println(“I am talking.”);
}
}

public class Alien implements Talk { public class Cat implements Talk {

public void talk() { public void talk() {


System.out.println(“zzzfer342aa”); System.out.println(“meow”);
} }
}
public void talking() {
System.out.println(“Overridden in Cat”);
}
}

Subclass may override the default


method if needed

The University of Sydney Page 45


Demonstration

The University of Sydney Page 46


See you next time!

The University of Sydney Page 47

You might also like