I am attempting to write a class that contains 2 private variables, however whenever I attempt to compile I am given error:
<identifier> expected for both setx and seti methods.
class complex
{
private double x;
private double i;
public void setx(x1) {x=x1;}
public void seti(i1) {i=i1;}
}
You have to write the data type as well (double in this case):
public void setx(double x1) {x=x1;}
public void seti(double i1) {i=i1;}
Actually the most Java way I recommend you is using the keyword this that refers to an instance variable. Moreover according the conventions name any class with a capital letter:
class Complex {
private double x;
private double i;
public void setX(double x) {
this.x=x;
}
public void setI(double i) {
this.i=i;
}
}
Related
So I'm trying to edit an object's x value from a method in a different class. The real reason I'm doing this is far more complicated but I just wanted to simplify things.
I am creating a game and I want the object that belongs to the first Class to be updated throughout the game. However when I try to update it, it appears in the other class however as soon as scope is returned to the first class the x value remains 0.
I have been struggling with this for hours...
public class first {
private second Second;
public void view() {
System.out.println(this.Second.x);
}
public void newObj() {
Second = new second();
}
public void changeObj() {
Second.changeX(4);
Second = Second.getSecond();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
first First = new first();
First.newObj();
First.changeObj();
First.view();
}
}
public class second {
public static int x=0;
public second getSecond() {
return this;
}
public second(){
x=0;
}
public static void changeX(int x) {
x = x;
System.out.println(x);
}
public int getX() {
return x;
}
}
You're encountering this because of the way the assignment is done:
x=x;
Just doing this should trigger a warning message "The assignment to variable x has no effect". This is because you're not referring to the static variable x but the argument itself.
Each non-static variable exists in the context of an object. In this case x is static so the usage of this.x = x; in a static context is not possible either. The correct approach is
Second.x = x;
public class DemoClass {
public void setValue(int a, int b)
{
int x=a;
int y=b;
}
public void getValue()
{
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
In the above program I have two methods setValue() and getValue(). SetValue method has two variables x and y which are assigned values 10 and 20(from the main method).
Now I want to display the value of x and y variables in getValue() method. But this is not possible as they are local variables. Is there any possible way of doing this?
Is there any possible way of doing this?
The usual thing is to make them fields of the class, specifically instance fields:
public class DemoClass {
private int x; // These are
private int y; // instance fields
public void setValue(int a, int b)
{
this.x = a;
this.y = b;
}
public void getValue()
{
// Use `this.x` and `this.y` here
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
dc.setValue(10, 20);
dc.getValue();
}
}
It's relatively rare to set two separate fields with a single setValue method, but there are use cases. Normally you'd have setX and setY (and getX and getY).
You could set them as public, or if you want to use getters and setters, you can do this.
public class DemoClass {
private int x;
private int y;
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
You can also put information in a constructor function like so:
public class DemoClass {
private int x;
private int y;
public DemoClass() {
this.x = 0; // default value
this.y = 0; // default value
}
public void setValue(int a, int b)
{
this.x=a;
this.y=b;
}
public void getValue()
{
System.out.println(this.x);
System.out.println(this.y);
}
public static void main(String[] args)
{
DemoClass dc=new DemoClass();
tc.setValue(10, 20);
tc.getValue();
}
}
That way, when you create the object like:
DemoClass demoClass = new DemoClass();
It will already have those objects set. If you don't do this and accidentally call getValue() and nothing is set, you will get a nullPointerException.
In C++ I could use 1 class throughout multiple files and when I modify a value using a function from one file, it would change that value globally.
In Java every file has to have it's own class; when I change a value using a method from one file, it does not change this value globally.
For example in C++ the files might look like this:
someClass.h
class someClass{
private:
int x;
public:
//Constructor
someClass(){
x = 5;
}
void changeVariable(); //Declaring function for later
}
main.cpp
int main(){
someClass cClass;
cClass.changeVariable(); //Call function
cout << x; //outputs 6
}
fileA.cpp
void someClass::changeVariable(){
x = 6; //x is changed to 6 globally.
}
In Java:
someClass.java
public class someClass {
int x;
//Constructor
public someClass() {
x = 5;
}
main.java
public class main {
public static void main() {
someClass cClass = new someClass();
subClass cSub = new subClass();
cSub.changeVariable();
System.out.print(x); //outputs 5
}
}
fileA.java
public class fileA extends someClass {
void changeVariable() {
x = 6; //x is changed to 6 only for fileA
}
}
My question is how can I change a variable from the sub class so that the variable is changed globally (For Java). Sorry if the question is still confusing.
Try with this:
public class someClass {
static int x;
//Constructor
public someClass() {
x = 5;
}
That a variable where static means that its value is common for all objects of the same class. That only one variable x is created for all, not one for each object.
Read that answer if you want a good explication of what static means:
What does the 'static' keyword do in a class?
Expose a function. setXyz in parent
public class someClass {
int x;
//Constructor
public someClass() {
x = 5;
}
public void setX(int n){
this.x = n;
}
}
public class fileA extends someClass {
void changeVariable() {
setX(6);
}
No need for static variable, this is the most equivalent thing you can do in Java:
public abstract class SomeClass {
protected int x = 5;
public abstract void changeVariable();
}
public class FileA extends SomeClass {
#Override
public void changeVariable() {
x = 6;
}
}
SomeClass doesn't have to be abstract of course, but you would have to implement it's changeVariable method.
Also x cannot be private, it has to be protected, so that it can be accessed by subclasses.
The following class contains a method that should calculate the integral using the callback technique.
package integrals;
import java.lang.*;
public class Integrals
{
public static double f1(double x)
{
return x*5+Math.sin(x);
}
public static double f2(double x)
{
return Math.pow(x*f1(-x),x);
}
public static double TrapezoidalIntegration(double a,double b,int n,double (*f)(double))
{
double rValue=0;
double dx;
dx=(b-a)/n;
for(double i=f(a);i<f(b);i+=dx)
rValue+=((f(i)+f(i+dx))*dx)/2.0;
return rValue;
}
public static void main(String[] args)
{
}
}
How to make a callback in this case? I prefer to avoid ☞such solution☜ due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.
How to make a callback in this case? I prefer to avoid such solution due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.
Since there are no function pointers in Java, you have to use a common interface instead. Your functions then have to be implementations of that interface. It is up to you whether you want to use names for those implementing classes (i.e. class F1 extends Function { … }) or anonymous classes instead (i.e. new Function { … }). It is also up to you whether you write the imp0lementation inside that class, or instead have the class implementation call one of your existing static functions.
Taking one example, with anonymous classes directly containing the implementation:
public class Integrals
{
public interface Function {
double eval(double x);
}
public static final Function f1 = new Function() {
public double eval(double x) {
return x*5+Math.sin(x);
}
};
public static final Function f2 = new Function() {
public double eval(double x) {
return Math.pow(x*f1.eval(-x),x);
}
};
public static double TrapezoidalIntegration(double a,double b,int n,Function f)
{
// … using f.eval(x) to compute values
This answer is valid for Java 7 or less that doesn't support closures nor callbacks.
First define an abstract class or an interface with a method that will calculate the integral value. For this sample, I'll define an interface:
interface IntegralCalculation {
double getIntegralValue(double x);
}
In your actual code, let's replace double (*f)(double) parameter for the interface and the method to use:
public static double TrapezoidalIntegration(double a,double b,int n, IntegralCalculation integralCalc) {
double rValue;
double dx;
dx=(b-a)/n;
// for(int i=f(a);i
Now, in your main method (or anywhere else where you will call this TrapezoidalIntegration method), pass an implementation of the interface. You can pass an instance of a class that implements the interface or an anonymous class.
Example using a class instance of a class that implements the interface (sorry, don't know other way to say it):
class BasicFunction implements IntegralCalculation {
#Override
public double getIntegralValue(double x) {
return x*5+Math.sin(x);
}
}
public class Integrals {
public static void main(String[] args) {
double x = TrapezoidalIntegration(0, 10, 10, new BasicFunction());
}
}
Using an anonymous class:
public class Integrals {
public static void main(String[] args) {
double x = TrapezoidalIntegration(0, 10, 10, new IntegralCalculation() {
private double f1(double x) {
return x*5+Math.sin(x);
}
#Override
public double getIntegralValue(double x) {
return Math.pow(x*f1(-x),x);
}
});
}
}
From the code above:
You can't pass a function pointer in Java, so double (*f)(double) parameter would be invalid, instead, we use an abstract class or an interface. IMO an interface would be better.
Once you have designed the interface, it must have a method that satisfy the rules of your function pointer. In this case, double (*f)(double) means a method that has a double as parameter and returns a double value. This is handled by getIntegralValue method.
After replacing the function pointer by the interface as parameter in TrapezoidalIntegration method, you should call the getIntegralValue as if it were the function pointer:
for(int i = integralCalc.getIntegralValue(a);
i < integralCalc.getIntegralValue(b); i += dx) { ... }
Does the this prefix for accessing member variables exist in Java?
Here is my HelloWorld code:
public class HelloWorld {
public static int x = 0;
public static void main(String[] args) {
HelloWorld.x = 45;
System.out.println(HelloWorld.x);
}
}
The above code works with/without the class name prefixing the variable x. However, if i try: this.x = 45; or this->x = 45; I receive an error:
non-static variable this cannot be referenced from a static context
I understand member variables can be accessed without the HelloWorld (class name) prefix, like I have done. But, I want to know if the this prefix exists in Java, how do I use it?
EDIT:
Also, could you provide an example where this is appropriate?
duffymo & byte - I greatly appreciate your help. Thanks.
Java has this as a prefix, but it's a reference to the current instance.
Static methods and attributes are associated with a class, not an instance, so you can't use this inside a static method.
public class HelloWorld {
public int x = 0; // note: now it's an instance attribute
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
System.out.println(hw.x);
}
public int getX() { return this.x; }
public void setX(int x) { this.x = x; }
}
You're attempting to use 'this' to refer to a static, not an instance variable. 'this' is only used to refer to the instance variables of an instantiated object of this class. You cannot use 'this' to refer to static variables on a class.
When you use 'this' you are saying "I want to refer to the variables of this particular instantiation of this class". A static on the other hand is always going to be the same variable for the class, irrespective of instantiation.
In addition the correct syntax for referring to an instance variable is by the dot operator:
this.x = 42; //correct
this->x = 42; //will not compile as its not valid Java
So essentially what you're after is something like the following:
public class Foo {
private int x;
public void setX(int x) {
this.x = x;
}
public int getX() {
return this.x;
}
}
public class HelloWorld {
public static void main(String[] args)
{
Foo foo = new Foo();
foo.setX(45);
System.out.println(foo.getX());
}
}
Remove the static modifier from your variable and then try it with this. Here is the difference:
Static variables exist only once in the whole program. No matter where you are, you could refer to HelloWorld.x and it would always be the same thing. That means, as you've declared it, anyone can modify it too, which may or may not be a good thing.
Member variables (not declared with static) are local to an instance of a class, which means you have to have created an instance with new before you can use it. However, every time you use new to create a new instance of that class, its non-static fields will be different. That is why you have to use this or, if in a different class, a reference to a specific instance in order to access them.
A clarification:
in getter methods it's not necessary to use the keyword this (as it's been shown in other answers). If you're new to Java this will introduce you to variable scopes (local variables vs instance variables). In other words the following works perfectly:
public class Foo {
private int x;
public void setX(int x) {
this.x = x; //Here the keywork this is necessary!
}
public int getX() {
return x; //in this case the 'x' can only be instance variable
}
}
There is also another important use of this for invoking constructors defined in the same class (You might want to check the keyword 'super' as well). Check the following:
public class HelloWorld {
public static void main(String[] args) {
Foo foo1 = new Foo();
Foo foo2 = new Foo(3, 4, 5);
System.out.println("Foo1:\n" + foo1);
System.out.println("Foo2:\n" + foo2);
}
}
class Foo {
private int x, y, z;
public Foo() {
this(-1, -1);
}
public Foo(int x, int y) {
this.x = x;
this.y = y;
}
public Foo(int x, int y, int z) {
this(x, y);
this.z = z;
}
#Override
public String toString() {
return "x= " + x + "\ny= " + y + "\nz= " + z + "\n";
}
}
Enjoy!
You can only use "this" from within an object instance.
"static", by definition, is OUTSIDE of ANY object.
Here's an excellent link in the Java documentation:
http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html
'Hope that helps!
for static variables, use ClassName (like you did). For instance (non-static) variables, use this.variableName
you can use it to access instance variables and methods, you are getting this error because you are using this to access static variables.
and also ... java doesn't have =>, in java you use the .
objectName.variableName = newValue
Use this for getters/setters/constructors.
For example.
class Test {
int x;
int y;
public void Test(int x, int y) {
this.x=x;
this.y=y;
}
public void setX(int x) {
this.x=x;
}
}