Weird 'static' in Java..

Very weird, indeed!


Example #1

class Animal {
    static String name = "Animal";
}

class TestClass {
    public static void main(String[] args) {
        System.out.println(Animal.name);
    }
}
Easy right?
Animal

Example #2

class Animal {
    static String name = "Animal";
}
 
class TestClass {
    public static void main(String[] args) {
        final Animal animal = new Animal();
        System.out.println(animal.name);
    }
}
Not so difficult?
Animal

Example #3

class Animal {
    static String name = "Animal";
}
 
class TestClass {
    Animal animal;
    public static void main(String[] args) {
        final TestClass testClass = new TestClass();
        System.out.println(testClass.animal.name);
    }
}
Are you expecting a NullPointerException? Gotcha!
Animal

Example #4

class Animal {
    static String name = "Animal";
}
 
class Lion extends Animal {
}
 
class TestClass {
    public static void main(String[] args) {
        System.out.println(Lion.name);
    }
}
Another easy one, no?
Animal

Example #5

class Animal {
    static String name = "Animal";
}
 
class Lion extends Animal {
    static String name = "Lion";
}
 
class TestClass {
    public static void main(String[] args) {
        System.out.println(Lion.name);
    }
}
Still easy..
Lion

Example #6

class Animal {
    static String name = "Animal";
}
 
class Lion extends Animal {
    static String name = "Lion";
}
 
class TestClass {
    public static void main(String[] args) {
        final Animal lion = new Lion();
        System.out.println(lion.name);
    }
}
Tricky, somewhat..
Animal

Example #7

class Animal {
    static String name = "Animal";
}
 
class Lion extends Animal {
}
 
class TestClass {
    public static void main(String[] args) {
        final Lion lion = new Lion();
        System.out.println(lion.name);
    }
}
What is the output?
Animal

Example #8
class Animal {
    static String name;
    static {
        name = "Animal";
    }
}
 
class Lion extends Animal {
    static {
        name = "Lion";
    }
}
 
class TestClass {
    public static void main(String[] args) {
        System.out.println(Animal.name);
        System.out.println(Lion.name);
        new Lion();
        System.out.println(Animal.name);
        System.out.println(Lion.name);
    }
}
So..? What do you think?
Animal
Animal
Lion
Lion

Example #9
class Animal {
    static String name;
    static {
        name = "Animal";
    }
}
 
class Lion extends Animal {
    static String name;
    static {
        name = "Lion";
    }
}
 
class TestClass {
    public static void main(String[] args) {
        System.out.println(Animal.name);
        System.out.println(Lion.name);
        new Lion();
        System.out.println(Animal.name);
        System.out.println(Lion.name);
    }
}
Will this change anything?
Animal
Lion
Animal
Lion