Find the Error The following class definition has an error W
Find the Error The following class definition has an error. What is it? public class MyClass {private int x; private double y; public static void setValues(int a. douable b) {x = a; y = b;}}
Solution
yes there is any error
In the setValues() method is accessing x and y which are non static so it gives you error
non-static variable x cannot be referenced from a static context
non-static variable y cannot be referenced from a static context
to run this code we need to either remove static keyword in setValues() method or add static to x and y.
Solution 1: (remove static)
public class HelloWorld{
private int x;
private double y;
public void setValues(int a,double b)
{
x = a;
y = b;
}
}
Solution 2:(add static to x and y)
public class HelloWorld{
private static int x;
private static double y;
public static void setValues(int a,double b)
{
x = a;
y = b;
}
}
In my opinion solutin 2 correct
