Reputation: 830
I am trying to master the fundamentals of Java and OOP. From my understanding, if I have an object Circle
that is instantiated with the variable radius, and passes that to a double
x, should methods of the Object be able to access these?
package classes;
public class Circle {
Circle(double radius) {
double x = radius;
}
double area() {
return x * x * 3.1415; // x can't be resolved to a variable
}
}
Upvotes: 0
Views: 100
Reputation: 149
Try this code :
public class Circle {
private double x =0.0;
Circle(double radius) {
this.x = radius;
}
double area() {
return this.x * this.x * Math.PI;
}
}
Upvotes: 0
Reputation: 31710
In your example, the double x
is limited in scope to the constructor. If you move it out to the object level, it will work as you expect.
public class Circle {
private double x;
Circle(double radius) {
this.x = radius;
}
double area() {
return x * x * 3.1415;
}
}
Upvotes: 0
Reputation: 1108
After defined at class level use 'this' for readiblity.
public class Circle {
private double x =0.0;
Circle(double radius) {
this.x = radius;
}
double area() {
return this.x * this.x * 3.1415; // x can't be resolved to a variable
}
}
Upvotes: 0
Reputation: 34166
Here you have a scope problem. When you declare x
inside the constructor, you are telling that it will only be accessible inside it.
You may want to declare it outside:
public class Circle {
double x;
Circle(double radius) {
x = radius;
}
...
}
Upvotes: 0
Reputation: 159844
x
is only available within the scope of the Circle constructor. Declare it at class level so it can be accessed by the area
method
public class Circle {
private double x;
Circle(double radius) {
this.x = radius;
}
...
}
Upvotes: 3