JAVA neutron class calls the parent class function execution order

JAVA method in a subclass if the parent class overrides the method, then calls the subclass direct method in a subclass of operation.

If the subclass does not override the method in the parent class, then subclass object can still call the non-private methods of the parent class, but then attribute methods are related to the parent class attributes used; and if the quilt class to call the the parent class method in turn invokes the subclass has overridden, then the method will be executed in a subclass, the relevant attributes using the attribute subclass;

 

E.g:

class A {
    int x = 6;
    private int y = 2;
 
    public A(int a) {
        x = a;
    }
 
    int getz() {
        int z;
        z = x / y;
        return z;
    }
 
    void show() {
        System.out.println("x=" + x);
        System.out.println("y=" + y);
        System.out.println("z=" + getz());
    }
}
 
class B extends A {
    int x = 3, y = 5, z;
 
    public B(int a) {
        super(a);
    }
 
    int getz() {
        z = x + y;
        return z;
    }
}
 
public class Temp {
    public static void main(String[] args) {
        B num2 = new B(9);
        num2.show();
    }
}

 

Operating results are: 
X =. 9
 
Y 2 =
 
Z =. 8

 

Since class B does not show methods, so num2.show () method performs shwo A class, then the first two lines show the method to print values ​​of x, y are the properties of class A, (A class when the value of x is in the new B (9) is assigned when a call super (a)); and the third row show methods Getz () rewritten in class B, the call is of class B Getz () method.

Published 11 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/zhengyin_tmac/article/details/105098871