7 Interface
7 Interface
Final methods
If we have 2 classes Vehicle & House, you are not allowed to extend
both classes simultaneously
Example
Assume you have a class that represents a book
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
Coding…
public class Book implements Comparable<Book>{
if(this.numberOfPages !=specifiedBook.numberOfPages)
if(!this.title.equals(specifiedBook.title))
return this.title.compareTo(specifiedBook.title);
return this.author.compareTo(specifiedBook.author);
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
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;
}
}
System.out.println(area);
This code works just fine and the output will be 15.0 as expected!
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
interface MyInterface{
final int a = 100;
default void display(){System.out.println(“Hello”);}
}
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