I'm not really sure how to word the title nor this but I'll try to be as specific as I can. I have created a class that contains a constructor that allows me to create objects of "Circle" type, and this circle has an argument radius. Here is that class:
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius; // this.radius refers to the instance variable above
}
public Circle() {
}
public double getArea() {
double area = radius * radius * Math.PI;
return area;
}
public double getCircumference() {
double circumference = 2 * Math.PI * radius;
return circumference;
}
}
I think the methods contained in this code are straight forward. I create an object given a radius, and it computes the circumference and area.
I also have another class, CircleTester, where I have created 2 objects of Circle type, c1 and c2, with a radius of 5 and 10, respectively.
public class CircleTester {
public static void main (String[] args) {
Circle c1 = new Circle(5);
double circumference1 = c1.getCircumference();
double area1 = c1.getArea();
System.out.println("Radius of c1: " + c1.radius);
System.out.printf("The circle c1 with circumference %.3f has area %.3f%n", circumference1, area1);
Circle c2 = new Circle(10);
double area2 = c2.getArea(); //objectReference.methodName()
double circumference2 = c2.getCircumference(); //objectReference.methodName()
System.out.println("Radius of c2: " + c2.radius);
System.out.printf("The circle c2 with circumference %.3f has area %.3f%n", circumference2, area2);
}
}
I'm having errors with the following 2 lines:
System.out.println("Radius of c2: " + c2.radius);
System.out.println("Radius of c2: " + c2.radius);
The program is failing to recognize c2.radius as the instance variable "radius" is declared as private in the circle class.
My question is is there any way to allow the CircleTester program to read the values of the radius of each object, without changing the instance variable from private to public? c1.radius and c2.radius do not work - the error is "Circle.radius is not visible" (because it is private)**
The reason I don't want to make it public is because I've been told by my tutor that declaring an instance variable as public can be seen as bad programming, and we could possibly be penalized in the exam.
I'm sorry if this is vague or stupid - explaining has never been my strong point. I'm also fairly new to Java so I am not 100% sure if I'm using all my terms correctly.