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

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.

Related

"this" objects vs non-static objects

Consider this:
public class Test {
public static int numberOfInstances = 0;
public int myInstanceID;
public String myInstanceName;
The static variable doesn't need to be called within an instance, it's available everywhere like this:
Test.numberOfInstances
When creating an instance, I only do this into my constructor:
public Test(int id, String name) {
myInstanceID = id;
myInstanceName = name;
numberOfInstances += 1;
}
I've recently discovered the this keyword and have noted some of its uses:
public Test() {
this(numberOfInstances + 1, "newInstance");
numberOfInstances += 1;
}
From what I've noticed, the this keyword allows you to call another one of the class' constructors. It also allows you to do this:
public Test(int x, int y) {
this.x = x;
this.y = y;
}
With java, I highly disagree with this style; same variable names, and I don't see the point of using this, especially after looking at the docs example. I look at this:
public Test(int a, int b) {
x = a;
y = b;
However, the use of the this keyword isn't necessary; In my code, I have a variables in my class (e.g. xCoordinate) where I don't use the this keyword (it's not static).
What I've been struggling to understand is what the difference is between non-static variables and this variables. Is there a difference? In one of my classes (the Paddle for Pong), I have this:
public class Pong {
public int xCoordinate;
public int yCoordinate;
and so on...
I never use the this keyword anywhere, and the data is stored within it's own instance.
Bottom line, my question is what is the difference between non-static variables and this.variables. Is it a standard coding practice? Why would I ever you the this keyword on non-static variables?
I think you may have almost answered your own question. You provided the function
public Test(int x, int y) {
this.x = x;
this.y = y;
}
However, what do you think would happen if you wrote it this way instead?
public Test(int x, int y) {
x = x;
y = y;
}
Noticed that I removed the this in the second function. Therefore, x and y would just be referring to the local x and y variables. this allows you to specify that you actually want to use the non-static class variables x and y.
If, as is typical, the parameter variable names of a constructor (say x) are the same as fields of the class, then the field names are shadowed by the parameters passed.
this is used in this case to disambiguate: this.x denotes the field x. It makes perfect sense. this means "reference to the current instance".
So, statements like this.x = x; are quite common.
If you still continue to dislike the Java style, and you adopt m_x-style notation for class fields, then you can write m_x = x; in your constructor. As you rightly point out, this is then not required.
this is also used as the notation for delegating constructors, as you point out.
The "this" keyword allows you to difference between method and instance variables:
public class Point {
private int x;
private int y;
public void add(int x, int y) {
this.x += x;
this.y += y;
}
}
There is no this variables. It's just used to tell the compiler that the variable you want to change is the declared field and not the local variable, in case they have the same name.
For the constructor part, this is just a shortcut for classes which have multiple constructors. You can write the code once and just call that from the alternative constructors.
There is also a similiarly used keyword super, which allows you to call methods and constructors of the superclass:
public SomeClass(int x) {
super(x);
super.someMethod(); // even if we would have overridden someMethod(),
// this will call the one from the superclass
}
Here's one instance where you would need the 'this' keyword:
public class Pong {
public int xCoordinate;
public int yCoordinate;
public Pong (int xCoordinate, int yCoordinate) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
}

Constructor overloading same arguments

Suppose I have class with 2 fields: x and y, of type double. Is it possible to define 2 constructors so constructor1 will create object setting its x property to what parameter in constructor tell and y to default and constructor2 vice versa?
public class Test {
private int x;
private int y;
public Test(int x) {
this.x = x;
}
public Test(int y) {
this.y = y;
}
}
I'm trying something like that and I know that it wont work because of overloading rules
No, you can't do that. Typically you'd do something like:
private Test(int x, int y) {
this.x = x;
this.y = y;
}
public static Test fromX(int x) {
return new Test(x, 0);
}
public static Test fromY(int y) {
return new Test(0, y);
}
You might want to consider that pattern (public static factory methods which in turn call private constructors) even when you don't have overloading issues - it makes it clear what the meaning of the value you're passing is meant to be.
No, You cannot have two methods or constructors with the same signature. What you can do is have named static factories.
public class Test {
private int x;
private int y;
private Test(int x, int y) {
this.x = x;
this.y = y;
}
public static Test x(int x) { return new Test(x, 0); }
public static Test y(int y) { return new Test(0, y); }
}
Test x1 = Test.x(1);
Test y2 = Test.y(2);
No, x and y have identical types, so both constructors would have the same type signature and the method resolution is based on parameter type, not name; the compiler has no way of differentiation.
The compiler looks for "Test.Test(int)" regardless of what the name of the parameter is.
The language would need additional feature added, such as named parameters, to do what you want.
If Java ever gets a syntax like C# for property initialization, you'll be able to use that idiom, using a default no-args constructor.
Besides the alternatives of using explicit factory methods, you could pass in a HashMap for your parameters.
public Test(HashMap<string,int> args) {
if(args.containsKey("x"))
x = args.get("x");
if(args.containsKey("y"))
y = args.get("y");
}
But static factory methods are cleaner for most cases. If you need much more, you may need to consider why you need such an idiom in the first place, and revise your class design.

how to use different class function in java

Hi im new to java i am unsure how to use class function in java . my teacher gave us the point2d class and wants us to use the function in there. there is a function call distanceTo
// return Euclidean distance between this point and that point
public double distanceTo(final Point2D that) {
final double dx = this.x - that.x;
final double dy = this.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
i am not sure how am i suppose to implement this. this is my code
public static int calc(int amount)
{
for (int t = 0; t < amount; t++)
{
double current = 0;
double x = StdRandom.random();
double y = StdRandom.random();
Point2D p = new Point2D(x, y);
if ( current < distanceTo(Point2D p ) )
{
}
i tried to use distanceTo(p) and distanceTo(Poin2D) and nothing works.
Thanks in advance
As it is a class function, you need a reference to an instance of the class as well. In this case something like
Point2D b;
p.distanceTo(b); // Invoke distanceTo on b from the point of view of p
This is because your method needs 2 objects to be referenced. The invoking object p and the passed object b, in your function referred to as this and that respectively.
public static int calc(int amount) is static, and distanceTo is not.
For not being static, distanceTo requires an enclosing instance of an object, say: new Point2D().distanceTo(...).
You can then call distanceTo to you some Point2D you already have, say p2:
p2.distanceTo(p);
Or you can try turning distanceTo into a static method, that would receive two points as arguments:
public static double distanceTo(final Point2D one, final Point2D that) {
final double dx = one.x - that.x;
final double dy = one.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
And call it using just:
distanceTo(p, p2);
PS.: as an alternative, maybe your solution is to turn calc non-static. You should try it, maybe.
To call a non static method of a class use the . operator.
To call distanceTo, use following syntax:
p.distanceTo(p);
if it was static, use class name with . operator
Point2D.distanceTo(p);

How to deal with JavaDoc comment repetition?

I was wondering what the best way of documenting this potential Point class is:
public class Point {
/* the X coordinate of this point */
private int x;
/* the Y coordinate of this point */
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
My concrete concern lies with the repetition between the x and y attributes and their respective getters and setters, as well with the constructor arguments.
It's not that I'm developing a public API or anything of the likes, it's no problem for me to have a general comment regarding some variable and then having the getter and setter have just the same text, for instance. I'd just like to avoid comment repetition in my own internal code. Is there a way to tie getX() and the int x argument of the constructor to the x attribute, for instance?
Thanks
Is there a way to tie getX() and the int x argument of the constructor
to the x attribute, for instance?
No, not that I'm aware of. What I do:
don't comment getters (or setters) at all
if X needs contextual information and if it somehow represents (part of the) state of the class I document it in the class-level Javadoc only
One obvious convention would be not writing JavaDoc comments for trivial getters.

Java newbie: How to assign current state of object to another, without establishing reference?

Once again, I'm looking for a way to bypass this array problem, how? Is there any way other than clone()?
I'm asking because fighting with clone(), protection and implemention stuff didn't work for me...
//assuming you have proper class and constructor (point(int x, int y))
/*
point 7POINTSARRAY[]=new point[7];
for(int i=0;i<7;i++)
{
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
}
//This won't work, so...
*/
point B = new point(0,0); // You need this.
for(int i=0;i<7;i++){
7POINTSARRAY[i]=B; // And this.
//But I want to read and assign value only,
// not establish a reference, so it can work How?
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x);
Though desired output is A[1].x=1, it's been owerwritten several times, and now A[1].x = 7.
You need to a create a new point for every element of the array if you want them all to reference different objects:
for(int i=0;i<7;i++)
{
point B = new point(0,0); // Put this *inside* the loop
7POINTSARRAY[i]=B; // Now B is a new instance of point
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x); // should now print 1
I haven't changed your code formatting but improving that will make the above clearer and easier to understand.
Sorry but Java works only with references for complex objects. You should use and implement clone() correctly this can't be the problem. clone() is well defined approach.
Typical clone for first level class looks like following
#Override
public Object clone() {
try {
A ans = (A) super.clone();
// do complex stuff
return ans;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
the line
A ans = (A) super.clone();
does default clone, which includes cloning object but not it's members. You should cascade clone for members. Since clone() is a member, it has access to protected members of the parent.
If your parent is Cloneable you should write
#Override
public Object clone() {
A ans = (A) super.clone();
// do complex stuff
return ans;
}
because parent can't throw exception.
For example, if you have point class looking like follows
class point {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
then you should just fix it in the following way
class point implements Cloneable {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
to make it cloneable.
Then you will be able to write
point a = new point(1,2);
point b = (point) a.clone();
and you will get 2 separate copies.
the problem is with the line
7POINTSARRAY[i]=B
which means that each object in 7POINTSARRAY refer (or points) to the same object B.
so when you do inside the loop
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
you actually always changing B.
You should do instead:
for(int i=0;i<7;i++){
7POINTSARRAY[i] = new point(i,i);
}

Categories