Java

OOP GUIDE / WORK

 

CIRCLE CLASS 3 SOLUTIONS

 

 

TASK – PART 1 – STARTING CODE

 

No solution required.

 

 

TASK – PART 2 – ADDING TO THE CIRCLE CLASS

 

Here is my solution with the code that was provided in Part 1 displayed in green:

 

public class Circle

{

   public double radius;

 

   public Circle(double r)

   {

      radius = r;

   }

 

   public double area()

   {

      double a = Math.PI * radius * radius;

      return a;

   }

  

   public double circumference()

   {

        double c = 2 * Math.PI * radius;

        return c;

   }

  

   public double diameter()

   {

        double d = radius * 2;

        return d;

   }

  

   public String toString()

   {

        return "Circle: Radius=" + radius;

   }

}

 

Note: The area(), circumference() and diameter() methods could all easily have been coded as a single line instead of two lines.

 

 

TASK – PART 3 – TESTING THE CIRCLE CLASS


Here is my solution:

 

 

public class CircleTester

{

     public static void main(String[] args)

     {

           Circle c1 = new Circle(5);

           System.out.println(c1.area());

           System.out.println(c1.circumference());

           System.out.println(c1.diameter());

           System.out.println(c1);       //calling toString()

          

           Circle c2 = new Circle(1);

           System.out.println(c2.area());

           System.out.println(c2.circumference());

           System.out.println(c2.diameter());

           System.out.println(c2);       //calling toString()

     }

}

 

 

The above will output the following:

 

78.53981633974483

31.41592653589793

10.0

Circle: Radius=5.0

3.141592653589793

6.283185307179586

2.0

Circle: Radius=1.0