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

7 Interface

Uploaded by

Bin
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)
10 views

7 Interface

Uploaded by

Bin
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/ 31

Multiple inheritance

Vũ Thị Hồng Nhạn

([email protected])

Dept. of software engineering, UET

Vietnam National Univ., Hanoi


Content

 Interface (multiple inheritance)

 Final methods

 Static & dynamic bindings

10/23/2024 Interface - multiple inheritance Page 2


Multiple inheritance
 Extending a class is extremely helpful in many situations
 Sharing some common code between variations of the class
 Extending the functionality of a class without modifying it
 Leveraging polymorphism to treat different classes as if they were the same

 However, there is one major limitation in Java


 A class cannot extend more than 1 class
 i.e., multiple inheritance is not allowed in Java

10/23/2024 Interface - multiple inheritance Page 3


Multiple inheritance
 Why?
 Multiple inheritance can cause ambiguity if the base classes have
similar methods
 Java’s solution to this problem is Interfaces

10/23/2024 Interface - multiple inheritance Page 4


what is interface?
 An interface is like a façade or an outline of an imaginary class
 Its sole purpose is to be inherited by another class
 It only defines what needs to be done but not how to do it
 i.e., the interface lists the methods that must be included in the class doesn’t
provide any implantation code
 The implementation of these methods is the responsibility of the classes that
implement the interface
 Once a class implements that interface, you can instantiate objects as usual

10/23/2024 Interface - multiple inheritance Page 5


Why interface?
 Java introduced interfaces to address the problem of multiple
inheritance

10/23/2024 Interface - multiple inheritance Page 6


Example
 Build a class Caravan, which represents a hybrid of a vehicle and a house

 If we have 2 classes Vehicle & House, you are not allowed to extend
both classes simultaneously

10/23/2024 Interface - multiple inheritance Page 7


Example …
 A good solution would be to introduce interfaces

 The first interface, called Movable


 It would define the methods that any class capable of movement should
implement (e.g., Vehicle class)

 Another useful interface called Habitable


 It would define all the methods that should be included for any class
representing a habitable entity

10/23/2024 Interface - multiple inheritance Page 8


Example …
 Once we define those 2 interfaces, we can implement both of them
in the Caravan class at the same time

10/23/2024 Interface - multiple inheritance Page 9


Example …
java code

public interface Movable{

void move(int distance);

10/23/2024 Interface - multiple inheritance Page 10


Example …
java code…

public interface Habitable{

boolean canFit(int inhabitants);

10/23/2024 Interface - multiple inheritance Page 11


Example …
java code…
public class Caravan implements Habitable, Movable{
int max;
int location;
void move(int distance){
location = location + distance;
}
boolean canFit(int inhabitants){
return max <=inhabitants;
}
}

10/23/2024 Interface - multiple inheritance Page 12


Summary
 Interfaces define what a class should do but not how to do it
 Creating an interface is very similar to creating a class
 An interface’s sole purpose is to be implemented by one or more
classes
 you cannot create an instance (Object) from an interface
 It’s not reducing code repetition, it’s more about enforcing a good
design

10/23/2024 Interface - multiple inheritance Page 13


Comparable interface
 is a popular interface in Java
 includes a single method definition called compareTo() which takes an
object as an input parameter of the same type and compares both objects
 “this” object against the input argument object

 The main purpose of this interface is...


 To allow any class to describe how to compare two objects of that class against
each other
 This becomes particularly useful when sorting or searching for objects of that
types

10/23/2024 Interface - multiple inheritance Page 14


Comparable interface

Example
 Assume you have a class that represents a book

public class Book{


int numberOfPages;
String title;
String author;
}
 You are asked to implement the Comparable interface so that you can
sort the books according to the following criteria
 If a book has more pages than the other, then the book with the more pages go
first
 If both books have the same number of pages, then sort by the title
alphabetically
If both books have the same number of pages and the same title, then sort by the
author alphabetically

10/23/2024 Interface - multiple inheritance Page 15


Comparable interface

Analysis…
 Before we start coding, let’s go through how the compareTo() method should work
 This method takes a single input parameter,
 It compares the “specified” object against “this” object
 According to the documentation, there are 3 possible outcomes when comparing 2
objects

3 possible outcomes Method should return

“This” object is considered less than the A negative integer


“specified” object

“This” object is considered equal to the Zero


“specified” object

“This” object is considered greater than the A positive integer


“specified” object

10/23/2024 Interface - multiple inheritance Page 16


Comparable interface

Coding…
public class Book implements Comparable<Book>{

public int compareTo(Book specifiedBook){

if(this.numberOfPages !=specifiedBook.numberOfPages)

return this.numberOfPages - specifiedBook.numberOfPages;

if(!this.title.equals(specifiedBook.title))

return this.title.compareTo(specifiedBook.title);

return this.author.compareTo(specifiedBook.author);

10/23/2024 Interface - multiple inheritance Page 17


Final methods
Why final method?
 Being able to override any method could be dangerous
 If someone creates a class with a certain method, they assume this method
behaves in a certain way

 That’s why, if you want to protect your method from being overridden in a
child class, you can prefix it with the keyword final

10/23/2024 Interface - multiple inheritance Page 19


Example
 A final method can still be accessed by the child class (if the permissions
allow so), but cannot be overridden
 Hence you can guarantee that any final method will behave exactly like the
parent’s implementation

 E.g.,
public class Room{
private double width;
private double height;
public Room(double with, double height){
this.width=width; this.height=height;
}
public final double getArea(){
return width*height;
}
}

10/23/2024 Interface - multiple inheritance Page 20


Example…
 Now if another class extends Room, no matter what type of room it is
 it shouldn’t be allowed to override the method getArea() because the area
should always be calculated the same way

public class LivingRoom extends Room{


//The constructor simply call the parent’s constructor using super()
public LivingRoom(double width, double height){
super(width, height) ;
}
//Not allowed to override getArea() here
}

10/23/2024 Interface - multiple inheritance Page 21


Example…
 Since the method is public, it means that it’s also available in the
child class

LivingRoom myLivingRoom = new Livingroom(3,5);

double area = myLivingRoom.getArea();

System.out.println(area);

  This code works just fine and the output will be 15.0 as expected!

10/23/2024 Interface - multiple inheritance Page 22


Remarks on interface
Important points
 Interface is used to achieve multiple inheritance
 We cannot create instance of interface
 A class can implement more than one interface
 A class that implements interface must implements all the methods in
the interface

 All methods in an interface are implicitly public and abstract, unless they are default
or static methods
 All the fields are declared as public, static, and final

 An interface can extends one or many interfaces

10/23/2024 Interface - multiple inheritance Page 24


From JDK 8 onwards
 Bạn có thể cài đặt phương thức mặc định

interface MyInterface{
final int a = 100;
default void display(){System.out.println(“Hello”);}
}

class TestClass implements MyInterface{


public static void main(String[] args){
TestClass t= new TestClass();
t.dislay();
System.out.println(t.a);
}
}

10/23/2024 Interface - multiple inheritance Page 25


Static & dynamic binding
Static vs. dynamic binding
 Static binding refers to the process where the type of an object is
determined at compile-time
 I.e., when the compiler processes the code, it knows the exact class (or
type) of the object, which allow it to bind method calls or variable
references to their corresponding definition before the program run

 In case of dynamic binding, the type of object is determined at run


time, typically in the context of polymorphism
 Dynamic binding is slower than static binding

10/23/2024 Inheritance Page 27


Binding
 Private, final and static modifiers are bound at the class level
 i.e., methods and variables using these modifiers are resolved through
static binding at compile-time
 Other methods using dynamic binding at runtime based on the actual
object instance

 In general, overloaded methods are bonded using static binding,


while overridden methods are bonded using dynamic binding

10/23/2024 Inheritance Page 28


example static binding

Output:
print in superclass.
print in superclass.

Since the print method of superclass is static, compiler knows that it will not be
overridden in subclasses  compiler knows during compile time which print method to
call and hence no ambiguity
10/23/2024 Interface - multiple inheritance Page 29
Example dynamic binding
• Methods are not static
• During compilation, the
compiler has no idea as to which
print has to be called since
compiler goes only by
referencing variable not by type
of object
 the binding would be delayed
to runtime and therefore the
corresponding version of print

Output: will be called based on type on


print in superclass. object.
print in subclass.
10/23/2024 Interface - multiple inheritance Page 30
Remarks
 Cannot override static methods in java
 Cannot access a non-static variable in a static context
 i.e., in a static method, can access only to static variables because non-
static variables depend on the existence of an instance of a class.
 Same for static class (nested static class)

 Final method: cannot be overridden


 Final class: cannot be inherited

10/23/2024 Interface - multiple inheritance Page 31

You might also like