I have the following 2 classes:
class Animal { public static void staticMethod(int i) { System.out.println("Animal : static -- " + i); } public void instanceMethod(int i) { System.out.println("Animal : instance -- " + i); } } class Cat extends Animal { public static void staticMethod(int i) { System.out.println("Cat : static -- " + i); } public void instanceMethod(int i) { System.out.println("Cat : instance -- " + i); } public static void main(String[] args) { Cat myCat = new Cat(); myCat.staticMethod(1);
And when I launch Cat, I got the following results:
Cat : static -- 1 Cat : instance -- 2 Animal : static -- 3 Animal : static -- 4 Cat : instance -- 5
I can understand 1,2,3 and 5, but why number 4 is not: "Cat: static - 4"? My understanding would be this:
myAnimal = myCat means that "myAnimal" is now exactly the same as "myCat", so wherever "myAnimal" appears, you can replace it with "myCat" and get the same result, because everything inside myAnimal is the same as and everything is inside myCat, so "myAnimal.staticMethod (4)" should be the same as "myCat.staticMethod (4)" and the output should be: "Cat: static - 4", similar to "myCat.staticMethod (1) ", above.
But it doesn't seem so, why?
Frank source share