[Tutorial] Java Interfaces
Submit solution
Java
Points:
10
Time limit:
0.5s
Memory limit:
2M
Author:
Problem type
Allowed languages
Interface
Interface is another way to achieve abstraction in Java. Interface is simply a complete abstract class. The functions declared in the interfaces should be implemented in the class that implements (similar to extends) this interface. The class the implements the interface should override all the methods in the interface.
Example
/*
* Created: Ramaguru Radhakrishnan
* Date: 08-May-2023
*
*/
interface Shape {
public void area();
public void display();
}
// Subclass (implements Shape)
class Circle implements Shape {
public void area() {
// area() of Circle Class - Definition
System.out.println("[Interface Method in Circle] Area of Circle is PI*R*R");
}
// Method
public void display() {
System.out.println("[Interface Method in Circle] Calculating Area of Circle");
}
}
// Subclass (implements Shape)
class Rectangle implements Shape {
public void area() {
// area() of Rectangle Class - Definition
System.out.println("[Interface Method in Rectangle] Area of Rectangle is L*B");
}
// Method
public void display() {
System.out.println("[Interface Method in Rectangle] Calculating Area of Rectangle");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("[Main] Creating Objects Circle and Rectangle");
Circle myCircle = new Circle(); // Create a Circle object
myCircle.display();
myCircle.area();
Rectangle myRect = new Rectangle(); // Create a Rectangle Object
myRect.display();
myRect.area();
}
}
Comments