-2

I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}

i get an error which says: cannot find symbol

xxsurajbxx
  • 13
  • 2

2 Answers2

1

You instantiate objects (of a class). Your 'variables' are fields of that class. If the fields are not static (as in your code), they belong to the object and you have to pass the corresponding object to the method of the other class to access the fields.

So it should be

b.getSlope(a)

when calling the method and the implementation has to have that argument

 public int getSlope(c1 c) {
      return (c.y-c.y1)/(c.x-c.x1);
 }

If you like to have the fields belong to the class, they have to be static.

(Note that in Java - by convention - class names should start with a Capital letter).

Christian Fries
  • 16,175
  • 10
  • 56
  • 67
  • Except don't you mean public int getSlope(c1 c) ... since it's c1 that has the variables? Then, in c1's constructor, the call might look like this b.getSlope(this). Except, there were no values set, so the variables will all be zero. But they would need to pass an instance of c1 ... not c2, right? Other than that, yes, you have the answer. – Lotsa May 30 '20 at 15:54
  • _Instantiate_ means to "create an instance of". So you do _instantiate classes_. – Sotirios Delimanolis May 30 '20 at 16:08
0

Variables x, y, x1, y1 do not exist in your c2 class so your code will never compile.

If you want to use x, y , x1 and y1 in your c2 class, consider trying another method.