16 Interfaces
16 Interfaces
Recap
• Why abstraction
• What is abstract class
• What is abstract method?
• Rules for abstract methods
Introduction
• An interface in Java is a blueprint of a class.
– The interface in Java is a mechanism to achieve abstraction.
– There can be only abstract methods in the Java interface, not method body.
– It is used to achieve abstraction and multiple inheritances in Java.
– Interfaces can have abstract methods and variables.
– It cannot have a method body.
– Java Interface also represents the IS-A relationship.
– It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface.
• Since Java 9, we can have private methods in an interface.
Introduction
How to declare an interface?
• An interface is declared by using the interface keyword.
• It provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static and final by
default.
• A class that implements an interface must implement all the methods
declared in the interface.
Syntax
interface <interface_name>{
// declare constant fields
// declare methods that abstract by default.
}
Introduction
• The Java compiler adds public and abstract keywords before the
interface method.
• It adds public, static, and final keywords before data members.
Classes and Interfaces
• A class extends another class, an interface extends
another interface, but a class implements an interface.
Classes and Interfaces
interface printable{
void print();
}
class DemoA implements printable{
public void print()
{System.out.println("Hello");}
interface Drawable{
void draw();
default void msg(){System.out.println("default method");} Default Method in
}
class Rectangle implements Drawable{
Interface
public void draw(){System.out.println("drawing rectangle");}
}
class DemoInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
Static Method in Interface
Since Java 8, we can have static method in interface.
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class DemoInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle(); d.draw();
System.out.println(Drawable.cube(3));
}}
Abstract Class vs. Interface
Practice Program
Write a Java programming to create a banking system with three classes - Bank,
Account, SavingsAccount, and CurrentAccount. The bank should have a list of
accounts and methods for adding them. Accounts should be an interface with
methods to deposit, withdraw, calculate interest, and view balances.
SavingsAccount and CurrentAccount should implement the Account interface
and have their own unique methods.