Java Tutorial Series - Interface
This tutorial will cover basics of Interface, why do we use them and what are the certain rules we need to keep in mind while working on Interface.
Interface in Java -
Let's say there are multiple classes which have common function, so one class can extend only one parent class, in this case we will proceed with creating an interface and defining the method without a body. Classes which are implementing the interface must use all the methods defined in the interface.
Consider below example -
public interface CentralBank {
public void withdraw();
public void deposit();
}
//Class which is implementing CentralBank interface
public class HDFC implements CentralBank{
private String repo = 7;
private int withdraw_rate = 15;
private int deposit_rate = 18;
public HDFC(String repo) {
this.repo = repo;
}
public void FDRates() {
System.out.println("FD Rates");
}
@Override
public void withdraw() {
System.out.println("Withdrawal rate in HDFC is: "+ withdraw_rate);
}
@Override
public void deposit() {
System.out.println("Deposit rate in HDFC is :"+ deposit_rate);
}
//We can also use the reference variable of interface with object creation of Class for an example -
// CentralBank CB = new HDFC()
// CB.withdraw();
//However object of interface cannot be created.
CentralBank CB2 = new CentralBank(); //not possible, it will throw an error
- A class can only extend one parent class but a class can implement n number of interfaces.
Consider below example -
public interface CentralBank {
public void withdraw();
public void deposit();
}
//Class which is implementing CentralBank interface
public class HDFC implements CentralBank{
private String repo = 7;
private int withdraw_rate = 15;
private int deposit_rate = 18;
public HDFC(String repo) {
this.repo = repo;
}
public void FDRates() {
System.out.println("FD Rates");
}
@Override
public void withdraw() {
System.out.println("Withdrawal rate in HDFC is: "+ withdraw_rate);
}
@Override
public void deposit() {
System.out.println("Deposit rate in HDFC is :"+ deposit_rate);
}
//We can also use the reference variable of interface with object creation of Class for an example -
// CentralBank CB = new HDFC()
// CB.withdraw();
//However object of interface cannot be created.
CentralBank CB2 = new CentralBank(); //not possible, it will throw an error
- A class can only extend one parent class but a class can implement n number of interfaces.
Comments
Post a Comment