Source Code
// [Link]
// Demonstrates declaring and implementing an interface in Java
interface Shape {
double area();
double perimeter();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
[Link] = radius;
}
@Override
public double area() {
return [Link] * radius * radius;
}
@Override
public double perimeter() {
return 2 * [Link] * radius;
}
}
class Rectangle implements Shape {
private double length, breadth;
public Rectangle(double length, double breadth) {
[Link] = length;
[Link] = breadth;
}
@Override
public double area() {
return length * breadth;
}
@Override
public double perimeter() {
return 2 * (length + breadth);
}
}
class Triangle implements Shape {
private double base, height, sideA, sideB, sideC;
public Triangle(double base, double height, double sideA, double sideB, double
sideC) {
[Link] = base;
[Link] = height;
[Link] = sideA;
[Link] = sideB;
[Link] = sideC;
Page 1 of 3
}
@Override
public double area() {
return 0.5 * base * height;
}
@Override
public double perimeter() {
return sideA + sideB + sideC;
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(5),
new Rectangle(6, 4),
new Triangle(4, 3, 3, 4, 5)
};
[Link]("----- Area Calculator -----");
for (Shape s : shapes) {
[Link]("Shape: " + [Link]().getSimpleName());
[Link]("Area : %.2f%n", [Link]());
[Link]("Perimeter/Circumference: %.2f%n%n", [Link]());
}
}
}
Lab Task / Exercises
1. Modify the program to add a new class Square that implements the
Shape interface, and include it in the shapes array.
2. Add a default method describe() in the Shape interface that prints a
generic message, and call it for each shape.
3. Create a second interface Drawable with a method draw(), and make
one of the classes implement both Shape and Drawable to
demonstrate multiple interface implementation.
4. Declare an interface constant (e.g., PI = 3.14159) inside Shape and use
it inside the Circle class instead of [Link].
5. Write a short program that shows the compile-time error that occurs
when a class implements an interface but does not override all of its
abstract methods, then fix it.
Page 2 of 3
Evaluation (For Instructor's Use)
Criteria Marks Allotted Marks Obtained
Understanding of Interface concept 5
Correctness of source code 10
Successful compilation & execution 5
Lab task / exercises completed 5
Viva-voce 5
Total 30
Instructor's Signature: ____________________________
Page 3 of 3