Java .

Java Static

static variables

Variables that have the same value for the whole class, not just an instance. Below you can see the on line 12 and 13 how the instance (not static) variable catColor is accessed. However, on line 14 you see the different way in which the static variable animalType is accessed.
1 class Cat {
2     public static String animalType = "feline";
3     public String catColor;
4     Cat(String colorIn)
5     {
6         catColor = colorIn;    
7     }
8    
9    public static void main (String[] argsIn) {
10        Cat patches = new Cat("calico");
11        Cat percy   = new Cat("black and white");
12        System.out.println("the cat named Patches color is " +
            patches.catColor);
13        System.out.println("the cat named Percy   color is " +
            percy.catColor);
14        System.out.println("Patches and Percy are both " +
            Cat.animalType);
15    }
16 }    

static methods

Methods that are for the whole class, not just an instance. Below you can see the on line 20 and 21 how the instance (not static) method getCatColor() is accessed. However, on line 22 you see the different way in which the static method getAnimalType() is accessed. Note that you can never use the keyword "this" with a static variable.
1 class Cat {
2     private static String animalType = "feline";
3     private String catColor;
4     Cat(String colorIn)
5     {
6         catColor = colorIn;    
7     }
8     public String getCatColor()
9     {
10        return this.catColor;  
11    }
12    public static String getAnimalType()
13    {
14        return animalType;  //could also return Cat.animalType
15    }
16    
17   public static void main (String[] argsIn) {
18        Cat patches = new Cat("calico");
19        Cat percy   = new Cat("black and white");
20        System.out.println("the cat named Patches color is " +
            patches.getCatColor());
21        System.out.println("the cat named Percy   color is " + 
            percy.getCatColor());
22        System.out.println("Patches and Percy are both " +
            Cat.getAnimalType());
23    }
24 }
Comments
Sign in to be the first to comment on Java Static.