I am working on using separate classes in a Object-Oriented Programming program.
- Would you create the separate class and the program itself in separate .java files or the same?
As in:
public class filename {
// ... content
}
class name {
}
Can you use the Scanner within the separate class, or should you use it in the main() method?
If so, how?Suppose you have to use the Scanner in the main() method, and you declared a new variable input and initialized it as the Scanner input.
How would you set that as one of the variables in the separate class? Would you make a new object and do.
Example:
public class TestSimpleCircle {
public static void main(String[] args {
SimpleCircle circle1 = new SimpleCircle();
System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());
// Create a circle with radius 25
SimpleCircle circle2 = new SimpleCircle(25); System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
// Create a circle with radius 125
SimpleCircle circle3 = new SimpleCircle(125); System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
// Modify circle radius
circle2.radius = 100; // or circle2.setRadius(100) System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
}
}
class SimpleCircle {
double radius;
SimpleCircle() {
radius = 1;
}
SimpleCircle(double newRadius) {
radius = newRadius;
}
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * radius * Math.PI;
}
void setRadius(double newRadius) {
radius = newRadius;
}
}
...that (e.g. circle1.getArea())?
- When you create variables in a separate class, are they in any way connected to variables with the same name in the main() method or a different class?