开发者

What's wrong with this? Cannot find symbol. symbol - constructor

开发者_Python百科
public MyLine(double x, double y)
{

   MyLine p1 = new MyLine();

   p1.x = x;

   p1.y = y;

}

That's my code

and the error I get is

./MyLine.java:12: cannot find symbol

symbol  : constructor MyLine()

location: class MyLine

MyLine p1 = new MyLine();


Don't instantiate it inside the constructor. Just assign:

this.x = x;
this.y = y;

The error tells you that you don't have a no-argument constructor, but even if you had, the behaviour won't be as you expect


The error message tells you that you don't have a no-arguments constructor in your MyLine class.

You could create one to let that code compile.

However it looks like you're trying to instantiate a MyLine object inside the MyLine constructor. You almost certainly don't want to do this.

Instead you want to take the values passed as arguments and initialize the fields of the current object with them:

public MyLine(double x, double y)
{
   this.x = x;
   this.y = y;
}


Provide default constructor i.e. add

public MyLine(){}

and it doesn't makes sense you are creating local object to constructor and assigning values to is..

instead use

this.x=x;

this.y=y;


This line:

MyLine p1 = new MyLine();

should be removed. That's creating a new instance, you actually want to work with the instance you're creating (since you're in the constructor.) You're getting the error because you're calling a constructor from this line that doesn't exist, but you don't want to be doing that anyway.

You can use the this keyword to reference the current instance (which you need to do if the fields have the same name as the parameters, which in this case it looks like they do.)

So taking that into account, you'd end up with the following:

public MyLine(double x, double y) {
    this.x = x;
    this.y = y;
}


You're constructing an instance of MyLine inside what appears to be a constructor of MyLine. So the caller of the constructor you're writing will cause two objects to be allocated. Is that what you want?


Do you really mean to construct a new MyLine object while constructing another MyLine object?

Do you really mean to do:

public MyLine(double x, double y)
  {

     this();

     this.x = x;

     this.y = y;

 }


You really shouldn't instantiate a new MyLine inside your other constructor. Why not simply do:

public class MyLine {

  private double slope;
  private double constant;

  // creates a new line: f(x) -> m*x + b
  public MyLine(double m, double b) {
    this.slope = m;
    this.constant = b;
  }

  // ...
}


The problem is that once you create a constructor yourself, like public MyLine(double x, double y) the compiler won't add the public MyLine() default constructor automatically.

If you want to make this a factory method you should return p1 and maybe make it static.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜