Object example to find area of a circle

All circles have the properties of (nouns)

radius
diameter
circumference
perimiter
area

What does the circle do? What can you do with a circle? (Verb)

Code Example 1:

public class James {

	public static void main(String[] args) {
	
	Circle c = new Circle(); // Circle() will assign 0.0 to radius and area
	System.out.println("Radius is " + c.radius);
	
	c.radius=3.5;
	c.area=3.14*c.radius*c.radius;
	System.out.println("Area is " + c.area);
	}
}

class Circle{
	double radius;
	double area;
}

Run:

Radius is 0.0
Area is 38.465

A much better way of coding this is to take the area calculation and put it in a method in the Circle class. This will then allow us to efficiently find the area of many circles but using the circle object properly.

Code Example 2:

public class James {

	public static void main(String[] args) {
	
	Circle c = new Circle(); // Circle() will assign 0.0 to radius and area
	c.findArea(3.5);
	}
}

class Circle{
	double radius;
	double area;
	
	public void findArea(double r){
		radius=r;
		area=radius*radius*3.14;
		System.out.println(area);
	}
}

Run:

38.465

Leave a Reply