Java - treatment of a sub-grade field if a copy is assigned to a super-class reference and field has the same names and default access retrofit



  • In studying the succession and polymorphysics in java, he came to such an example:

    class A {
     int a = 5;
     String doA() {
      return“ a1“;
     }
     protected static String doA2() {
      return“ a2“;
     }
    }
    class B extends A {
     int a = 7;
     String doA() {
      return“ b1“;
     }
     public static String doA2() {
      return“ b2“;
     }
     void go() {
      A myA = new B();
      System.out.print(myA.doA() + myA.doA2() + myA.a);
     }
     public static void main(String[] args) {
      new B().go();
     }
    }
    

    Programme result: "b1 a2 5"

    1. b1 is understandable. The actual type of class is B, the dynamic connection of the compiler causes the method doA() defined in Class B.

    2. a2 - doA2() is defined as static, as is the case in the past, the compiler shall produce a class A method rather than a copy

    3. 5 is here for me and there is magic. Why not 7?



  • A myA = new B();
    ^
    Because fields Java is not polymorph, the index class is used accordingly. A

    On methods: Java All methods are virtual, and therefore dynamic (or, as already referred to, later) connecting. Therefore, the implementation phase JVM Type of facility Bto which the index refers myA and causes appropriate implementation doA() Class B




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2