Static method(Class method) and Instance method

  • Summary

  1. static method call static method? O

  2. static method use instance variable? X

  3. static method use instance method? X

  4. why? When call static method, object(iv group) might not exist!

Static method = class method

Depend on whether using IV(Instance Variable) or not.

Instance Method

Static Method

call

referencetype_var_name.methodname()

class_name.methodname()

IV(Instance Method)

use IV

Not use and non-related with IV

  • Static method example : Math.random(). No need to create object(reference type variable).

class MyMath2 {
    long a,b;
    
    long add() {//no parameter
        return a+b;//using iv
    }
    static add(long a, long b) {//parameter => local variable
        return a+b;//parameter a and b
    }
}
class MyMathTest2 {
    public static void main(String args[]) {
        System.out.println(MyMath.add(200L,100L));//call class method
        
        //instance method
        MyMath2 mm = new MyMath2();
        mm.a = 200L;
        mm.b = 100L;
        System.out.println(mm.add());//call instance method
    }
    
}

think about making static method.

=> when NOT using iv and im!

static variable : common properties.

CV(Class variable) , CM(Class Method) are available without creating object

IV, IM are non-available before creating object.

Last updated