Thursday, September 15, 2011

Instantiation

This program shows how you create an object/instance of a class, and call methods in the created object.

browse

package org.megha.blog.example.part2;

/**
 * A Circle that can calculate it's area and perimeter.
 */
public class Circle {

	private double radius;

	/** 
	 * Constructor to create a circle of a given radius.
	 * Note: how you cannot create a Circle without specifying it's radius!
	 */
	public Circle(double radius) {
		this.radius = radius;
	}

	/** @return the radius of the circle */
	public double getRadius() {
		return radius;
	}

	/** @return the area of a circle (PI*r*r) */
	public double getArea() {
		double area = Math.PI*radius*radius;
		return area;
	}

	/** @return the perimeter of the circle (2*PI*r) */
	public double getPerimeter() {
		double perimeter = 2 * Math.PI * radius;
		return perimeter;
	}

	/** prints the radius, area and perimeter of this circle */
	public void print() {
		System.out.println("Circle, with radius  " + getRadius());
		System.out.println("Area = " + getArea());
		System.out.println("Perimeter = " + getPerimeter());
	}

	public static void main(String args[]) {
		// create a circle of radius 10
		Circle circle1 = new Circle(10);
		// print information about the circle we just created
		circle1.print();
	}
}

No comments:

Post a Comment