0

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
    }

}

5 Answers 5

3

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;
    }

    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }

    ...
}

Comments

0

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
    }

}

Comments

0

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; 
    }

}

Comments

0

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;
       }

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.