Object Oriented Programming

Interfaces in Java

An interface provides a framework for a class. It gives method signatures and constants to the class to be implemented. A class that uses an interface implements the interface.


Syntax
modifier interface interfaceName {
    //constant declarations    
    //method signatures
}

modifer class className implements interfaceName {
   //methods from the interface
}; 

Notes

An interface only contains method signatures and constants, which means it contains no implementation code. All method signatures must be given implementation in any class that implements the interface,


Example
public interface Country {
    //all classes that implement Country must have the method getCapital()
    public String getCapital(); 
} 
 
public class NACountry implements Country {
    String capitalCity;    
    public NACountry(String capitalCity) {
        this.capitalCity = capitalCity;        
    }    

    public String getCapital(){ //implemented method signature from the interface
        return capitalCity;
    }
} 

< Inheritance   |   Abstract Methods and Classes >

© 2019 SyntaxDB. All Rights Reserved.