Home > Net >  Create Method that edits values of Custom Class in Java. i.e:
Create Method that edits values of Custom Class in Java. i.e:

Time:11-21

I had a quick and most likely simple question regarding the creation of a method that edits the values within the class object. Bellow is a highly simlified example. There is a a class titled "num" which contains a single interger titled obj. The num() method takes and assigns the input of an integer. I am in need of a way to edit that obj value by adding 1 that can be strucuted like so: num testcase=new num(4).addone(); or simply: num(4).addone(); I understand there are other ways to do this but unforunately I need it to be done like this. My desired output for this would be a new "num" object containg the integer value 5 stored in obj. Essentially I need the object to be created and then edited through the adddition of 1. If anyone could either provide me a solution, give me the correct termonology for this for further research, or any help would be greatly appreciated. I understand the example below does not work but I was just giving an example. Thank you for any help you can provide.

public static class num{
    //simple class containing single integer
    int obj; 
    public num(int input){
    //method creating num class object 
        this.obj=input;
    }
    public addone(){
         //rudimentary attempt at creating such function. 
        this.obj=obj 1;
    }
        }
    public static void main(String[] args) {
        System.out.println("Hello World!");
        num testcase=new num(4).addone();
    }
}

I have tried a multitude of differnt ways to store the function and attempted to implement newinstance but dont quite understand this.

CodePudding user response:

In order for you to do the chained method call you need your method to actually return the instance of your class itself so it can resolve to the assignment instruction.

Here:

public class num {

    int obj; 
    public num(int input){
        this.obj=input;
    }
    //it needs to return the instance of the class itself
    public num addone(){
        this.obj=obj 1; //modify the obj attribute
        return this;  //return the instance of the class
    }

    public static void main(String[] args) {
        System.out.println("Hello World!");
        //Reason you need addone to return the instance of the class
        //is for the compile to resolve the below assignment as
        //you are assigning a Type "num" to testcase
        num testcase = new num(4).addone();
        System.out.println(testcase.obj); //this should print 5
    }
}

Here is a good read about it: https://www.geeksforgeeks.org/method-chaining-in-java-with-examples/

  • Related