Hi everyone,
I’m trying to get my head around static methods in a class.
Let’s say I want to create the following class:
class MyVector {
float v1, v2;
MyVector(float v1, float v2) {
this.v1 = v1;
this.v2 = v2;
}
}
Now let’s imagine that I want a way to create a unit vector to the right, something like this:
MyVector createUnitVector() {
return new MyVector(1, 0);
}
My first guess was to create a static method inside my MyVector
class like so:
class MyVector {
float v1, v2;
MyVector(float v1, float v2) {
this.v1 = v1;
this.v2 = v2;
}
public static MyVector createUnitVector() {
return new MyVector(1, 0);
}
}
But in order to do so, I need to also make my class static:
static class MyVector {
...
}
For now it’s okay, but let’s imagine that I want to add a randomize function:
static class MyVector {
...
public void randomize() {
v1 = random(1);
v2 = random(1);
}
}
Now I can’t do that since the random()
function is a non-static method of the PApplet class.
Of course I could simply put my function outside the class like so:
class MyVector {
float v1, v2;
MyVector(int v1, int v2) {
this.v1 = v1;
this.v2 = v2;
}
public void randomize() {
v1 = random(1);
v2 = random(1);
}
}
MyVector createUnitVector() {
return new MyVector(1, 0);
}
But is there a more “elegant” way to solve this?
Thanks