Additional information on
interfaces
Additional information on
interfaces
- instanceof:
- Examples:
Circle a = new Circle("red", 2);
BankAccount b = new BankAccount(100);
Because Circle implements ComparableThing:
a instanceof ComparableThing ---> true
Because BankAccount implements ComparableThing:
b instanceof ComparableThing ---> true
|
|
Quiz on
instanceof
- Suppose the
class Dog is
defined as:
class Dog extends Animal implements Pet
{
...
}
Dog fido = new Dog();
|
Answers:
all are true...
fido instanceof Dog true (self)
fido instanceof Animal true (superclass)
fido instanceof Pet true (interface is like superclass)
fido instanceof Object true (super-superclass)
|
|
A
scenario for
default implementation of
methods in an
interface
- You write a super cool interface.
You provide your interface
to a bunch of friends and they implement your interface
with various super
cool classes and deploy their code on their super cool websites....
- Later....
You realize you forgot to add one of your desired methods
to your interface.
- You edit your interface to add this abstract method....
Result:
- All of your friends'
super cool classes
won't compile
because they
haven't implemented
this
new method,
and their websites are unusable.
|
|
Methods with a
default implementation in
an interface
- You can define
methods with a
"default" implementation
in an interface
- Syntax to
declare
(abstract) methods
with a default implementation:
public interface InterfaceName
{
public default returnType methodName( params )
{
default method body
}
}
|
- Usage:
- When the implementing class
does not
override a
method with a
default implementation:
- The Java compiler will
use the
default implementation
as the overriding method
|
|
|
DEMO:
demo/05-interfaces/30-default-impl/MyInterface.java
+ MyImpl1.java
+ Demo.java
DEMO:
demo/05-interfaces/30-default-impl/MyInterface.java
+ MyImpl2.java (omit)
+ Demo2.java
Additional information on
interfaces
---
interface inheritance
- Unlike
classes that can
extend only
1 class,
interfaces
can extend
more than 1
interface
|
|
Comparing an
abstract class vs an
interface
Abstract class |
Interface |
- Can have constructors,
instance variables,
constants,
abstract methods and
non-abstract methods
(i.e.: Everything)
|
- Can only have
abstract methods and
constants
|
|
- Is implemented by
a subclass that
must
implement
all
the abstract methods
|
❮
❯