Java attributes

From wikinotes

modifiers

See java modifiers for more details.

class MyClass {
    int number = 0;
    static int cls_num = 10;
    final int maxhealth = 10;   // attempts to change value raise exception
    static int name = 10;       // access without instantiating object
}

this

this refers to the current instance. It is magically added to the scope.

class MyClass {
    int x = 1;
    public void increment_x(){
        this.x++;
    }
}

class attributes (static)

class MyClass{
    static int shared_num = 10;

    static void main(String args[]){
        MyClass a = new MyClass();
        MyClass b = new MyClass();
        a.shared_num = 15;
        System.out.println(a.shared_num);
        System.out.println(b.shared_num);
    }
}

outputs

15
15

instance attributes

class MyClass{
    int num = 10;

    static void main(String args[]){
        MyClass a = new MyClass();
        MyClass b = new MyClass();
        a.num = 15;
        System.out.println(a.num);
        System.out.println(b.num);
    }
}

outputs

15
10