javastatic-methodsclass-instance-variables

Relation between class instance and static methods


Is there any particular relation between class instance (e.g variables that declared by static/final) and static methods(e.g class methods) ?

I hop you understand what i mean.


Solution

  • Static and non-static methods/classes are entirely different beasts. Let's use an example of object-oriented programming. Say I have a class called "Person", with a constructor called Person(), with the instance variables declared as myAge (set as 0), and a method called Birthday():

    int myAge;
    
    public Person(){
        myAge = 0;
    }
    
    public void Birthday(){
        myAge += 1;
    }
    

    In my main method, this class would be used like this:

    Person Sajjad = new Person();
    Sajjad.Birthday();
    

    When I create a new person, which is you, your age is 0, because our constructor's default values are 0 for myAge. Once I apply the Birthday() method on you, your age goes up by one, through the increment.

    As for static methods, there's no object-oriented principles in it. There are uses for it.. I usually use it for simple math.

    public static double addValues(double a, double b){
        return a + b;
    }
    

    In my main:

    int sum;
    sum = addValues(1, 2);
    System.out.println(sum);
    

    Output:

    3

    See how above there's no need to declare a new objects? Static methods are easier to prototype, but in the long run I definitely go with object-oriented principles because it makes maintaining code in the long run so much easier. Also, I don't need to clutter my main method with unnecessary lines of code.

    P.S. If the code is wrong, it's really just some pseudo code I whipped up.