How can I have the Edit() method be called by default when I construct a Breuk object?
public class Breuk {
public Breuk() {//constructor
}
private static Breuk Edit (Breuk b){ //function
}
}
Every time a new Breuk object is created, the Edit() method is called by default since it is placed inside the constructor. As the method is static, it has to be called in a statically way, i.e. ClassName.staticMethod(). As the method expects a Breuk object as argument, you pass this reference to it, meaning the object that's being constructed.
By the way, all method names should be lowercase according to Java conventions. So, consider renaming Edit(...) to edit(...).
class Breuk {
int x;
int y;
public Breuk(int x, int y) {
Breuk.Edit(this);
}
private static void Edit(Breuk b){
//edits breuk
}
}
First of all, you should stick to Java naming conventions, which state that method names should be lowerCamelCase. So you should rename your Edit() method to edit().
If you want the edit() method to be called by default when constructing an instance of the Breuk class, you can use an initializer block.
Excerpt from the Java Tutorial:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
For your example, you could try something like this:
public class Breuk {
{ // initializer block
Breuk.edit(this); // always called by default,
// no matter which constructor is used
}
public Breuk() { // no-args constructor
}
public Breuk(int a1, int a2) { // another constructor
}
private static Breuk edit(Breuk b) { // function
}
}
Here I'm assuming you want to pass the instance being constructed to the edit() method, that's why this is passed as an argument.
EDIT:
In case this assumption is true, I suggest you make the edit() method return void, as you can't assign an instance to this, since it's final (and it doesn't make any sense, either).
Just call the method from the end of your default constructor. There's no need to think about any "default" calling here. Just implement it.
public class Breuk {
public Breuk() {
// constructor
edit(this);
}
private static Breuk edit (Breuk b){
// class-level processing on any Breuk that is constructed
}
}
private static Breuk Edit(Breuk b){?final.