I have some problems with manipulating an object.

M

mohed.haidar

Hello guys, happy new year.
Well, a very basic question. I make a class objekt that lookes
something like this :

public class circle {

public static final PI = 3.14159;
public double r;
public double area(double r) {
return r*r*PI;
}
}

and then from somewhere else I do :

circle.r = 5;
double area = circle.area(); <--- this gives me a compilation error,
it wants me to specify circle.area(5). I thought


that it was legitamet code to leave it at (). Is'nt it what object
oriented code was all about, i have already defined the objects
variable r to bee 5, shouldent need to further specify
circle.area(5).
Thank you for any response in advance.
 
O

Owen Jacobson

Hello guys, happy new year.
  Well, a very basic question. I make a class objekt that lookes
something like this :

public class circle {

  public static final PI = 3.14159;
  public double r;

This defines a member variable named 'r'.
  public double area(double r) {

This defines a method taking a parameter named 'r', unrelated to the
member variable. You probably meant
public double area () {
or more conventionally
public double getArea () {
        return r*r*PI;
  }

}

and then from somewhere else I do :

circle.r = 5;
double area = circle.area();  <--- this gives me a compilation error,
it wants me to specify circle.area(5). I thought

that it was legitamet code to leave it at (). Is'nt it what object
oriented code was all about, i have already defined the objects
variable r to bee 5, shouldent need to further specify
circle.area(5).

In Java, local variable names and parameter names hide member
variables with the same name. The following program is exactly
equivalent to your original program, but illustrates why you get an
error:

public class circle {
public static final PI = 3.14159;
public double r;
public double area(double r2) {
return r2*r2*PI;
}
}

-o
 
P

Patricia Shanahan

In addition to Owen's comments, PI needs a type. On the other hand, you
should probably get rid of it. Math.PI is a far closer approximation to pi.

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top