Analysis of the difference between coverage and hiding of Java methods

  • 2020-04-01 01:41:32
  • OfStack

For the difference between hiding and overwriting, mention RTTI (run-time type identification) (runtime type check), that is, runtime polymorphism, when a parent class reference points to a subclass object, Here's a piece of code I wrote:


public class RunTime {

    public static void main(String[] args) {
        Animal a = new Cat();
        System.out.println(a.A);
        System.out.println(a.b);
        a.voice();
        a.method();

    }
}
class Dog extends Animal {
    public int b = 3;
    public static int A = 3;
    public static void method(){
        System.out.println(" The dog ");
    }
    public void voice() {
        System.out.println(" The dog barks ");
    }
}
class Cat extends Animal {
    public int b = 4;
    public static int A = 4;
    public static void method(){
        System.out.println(" The cat ");
    }
    public void voice() {
        System.out.println(" meow ");
    }
}
class Animal {
    public int b = 0;
    public static int A = 0;
    public static void method(){
        System.out.println(" animal ");
    }
    public void voice() {
        System.out.println(" The animal is called ");
    }
}

The output is:
0
0
meow
animal

As you can see, when a reference to parent Animal points to a subclass Dog, RTTI automatically determines the true type of the reference at run time, when subclass & PI; Coverage   When the parent class method, directly call the subclass method, print out "meow"; However non-static methods rewrite the word is overridden in subclasses, and the method of static be subclasses override is hidden, in addition, static variables and member variables are hidden, and RTTI is only for cover, not for hiding in the shadows, so, static and non-static variables b and static method are through RTTI (), which is the references to classes whose static method is invoked, A member variable, and here is the parent class Animal references, so direct call the superclass methods and member variables in Animal. So the static method(),  The static variable A and the member variable b print all the results from the parent class. Only the overridden non-static method voice () is used to print subclasses.


Related articles: