Showing posts with label implements. Show all posts
Showing posts with label implements. Show all posts

Thursday, September 15, 2011

Interfaces

Here's an example to show how an interface (Shape) is defined, implemented (Square, Circle) and used (Main). Note: how Object.toString() is overriden and is used by printInfo()

browse

package org.megha.blog.example.part5;

/** An Interface for a shape that has an area and a perimeter */
public interface Shape {
	public double area();
	public double perimeter();
}

package org.megha.blog.example.part5;

/** A class that represents a circle */
public class Circle implements Shape {

	double radius;

	public Circle(double radius) {
		this.radius = radius;
	}

	public double area() {
		return Math.PI* radius*radius;
	}

	public double perimeter() {
		return 2*Math.PI*radius;
	}

	@Override
	public String toString() {
		return "circle of radius " + radius;
	}
}

package org.megha.blog.example.part5;

/** A square shape */
public class Square implements Shape {

	private double side;

	public Square(double side) {
		this.side = side;
	}

	public double area() {
		return side * side;
	}

	public double perimeter() {
		return 4 * side;
	}

	@Override
	public String toString() {
		return "square of side " + side;
	}
}

package org.megha.blog.example.part5;

/** Creates a square and a circle and prints their area and perimeter */
public class Main {

	private static void printInfo(Shape s) {
		System.out.println("for shape: " + s);
		System.out.println("area: " + s.area());
		System.out.println("perimeter: " + s.perimeter());
	}

	public static void main(String args[]) {
		Square square1 = new Square(5);
		printInfo(square1);

		Circle circle1 = new Circle(7);
		printInfo(circle1);
	}
}
Output of this program:
for shape: square of side 5.0
area: 25.0
perimeter: 20.0
for shape: circle of radius 7.0
area: 153.93804002589985
perimeter: 43.982297150257104