⬅ Previous Topic
Java int KeywordNext Topic ⮕
Java long Keywordinterface
Keyword⬅ Previous Topic
Java int KeywordNext Topic ⮕
Java long Keywordinterface
Keyword in Java
In Java, the interface
keyword is used to declare an interface. An interface is a blueprint of a class that contains only abstract methods (until Java 7) and static/final variables. Interfaces help achieve abstraction and support multiple inheritance in Java, which is otherwise not possible with classes.
Interfaces are useful when:
interface InterfaceName {
// constant variables
// abstract methods
}
interface Animal {
void makeSound(); // abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark!");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.makeSound();
a2.makeSound();
}
}
Bark!
Meow!
public
and abstract
(unless marked otherwise in Java 8+).public static final
.implements
keyword to implement an interface.abstract
.Aspect | Interface | Abstract Class |
---|---|---|
Multiple Inheritance | Supported | Not supported |
Constructors | Not allowed | Allowed |
Access Modifiers | Only public methods | Any access modifier |
Default Behavior | No state or constructors | Can have fields and state |
Since Java 8, interfaces can have:
default
methods — methods with a body.static
methods — utility methods tied to the interface.interface Calculator {
default void greet() {
System.out.println("Welcome to Calculator!");
}
static void info() {
System.out.println("Calculator Interface v1.0");
}
int add(int a, int b);
}
class BasicCalculator implements Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new BasicCalculator();
c.greet();
System.out.println("Sum: " + c.add(5, 3));
Calculator.info();
}
}
Welcome to Calculator!
Sum: 8
Calculator Interface v1.0
A functional interface is an interface with exactly one abstract method. These are the basis for lambda expressions.
@FunctionalInterface
interface Printer {
void print(String msg);
}
public class Main {
public static void main(String[] args) {
Printer p = (msg) -> System.out.println(msg);
p.print("Lambda says hi!");
}
}
Lambda says hi!
⬅ Previous Topic
Java int KeywordNext Topic ⮕
Java long KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.