John Doe
John Doe

Reputation: 3

How to build a method that increment the value of instance variable when it is called in main by an object?

I want to build a method that when it is called in main, automatically increment the value of variable.If first value is 0 when its called increment it to 1 , when I call for second time from 1 to be incremented at 2 and so on. Notes: The method is part of a class and it called via object in main.

Upvotes: 0

Views: 1014

Answers (2)

Dzone64
Dzone64

Reputation: 108

Well, you kinda left a lot up for interpretation here, assuming the "value of variable" is part of the object the code would be something like this:

public class MyClass {
    public int myVariable = 0;

    public MyClass() {}

    public void incrementMyVariable() { 
        myVariable++;
    }
}

How you would handle this depends on where the variable your referring to is located ie. main method, object variable, etc... Additionally, if the variable needs to be kept constant across all the objects created for the class you would need it to be static.

Upvotes: 0

Ayush Gupta
Ayush Gupta

Reputation: 83

you can use the static variables. Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. Create a static variable whose value can be updated in a function. let this be your class

class Student {
    static int b; //initialized to zero only when class is loaded not for each object created.

    public void update(){
       //incrementing static variable b
        b++;
    }

    public void showData(){
        System.out.println("Value of b = "+b);
    }

}

and this be your main class

public class Demo{
   public static void main(String args[]){
     Student s1 = new Student();
     s1.update();
     s1.showData();
     Student s2 = new Student();
     s2.update();
     s1.showData();
    }
}

output:

Value of b = 1
Value of b = 2

Upvotes: 1

Related Questions