开发者

Java constructors of classes

开发者 https://www.devze.com 2023-02-20 09:05 出处:网络
When I try to create a new instance of the class Point Point nir = new Point(double x, double y); I\'m getting the error

When I try to create a new instance of the class Point

Point nir = new Point(double x, double y);

I'm getting the error

Multiple markers at this line
   - x cannot be resolved to a variable 
   - y cannot be resolved to a variable

How come? I want x and y to be general, not specific. I want to include my Point as a field of a new class.

EDIT:

In a given class named Circle I want to replace the fields x0 and y0, that represent the coordinates of a point, with an object of type Point. So this is the begining of the class Circle that I want to refactor 开发者_开发问答as above:

public class Circle {

   private double x0, y0, radius;

So, I basically want to change the representation of x0, y0 to Point structure.


The error you're getting is that this code

new Point(double x, double y);

is not legal Java. When you create an object or call a function, you do not specify the types of the arguments. Instead, you just provide a value of that type. So, for example, you could create a point by writing

Point origin = new Point(0.0, 0.0);

Or

double x = 137.0;
double y = 2.71828;
Point myPoint = new Point(x, y);

Because in both cases the compiler already knows the types of the expressions you're providing as constructor arguments. You don't need to (and in fact should not) say that they're doubles.

Hope this helps!


Try this:

Point nir= new Point(x, y);

If that doesn't work, show more code.


You need to create the instance like so:

Point nir = new Point(x, y);

Or like so:

Point nir = new Point(15.0, 12.0);

where x and y are doubles. You're getting an error because you can't specify the type for arguments when calling a constructor, so Point nir = new Point(double x, double y); causes an error.


x and y have to already made:

so do:

Point nir = new Point(x, y);


You're trying to set the parameters when it's expecting arguments. Try:

Point nir= new Point(x, y);

Or:

Point nir= new Point((double) x, (double) y);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号