Home  >  Article  >  Java  >  What is the method for java subclass to call parent class?

What is the method for java subclass to call parent class?

coldplay.xixi
coldplay.xixiOriginal
2020-09-02 14:59:0419314browse

Java subclass calls the method of the parent class: 1. When the object of the subclass calls a method, it will first search in the subclass. If there is no such method in the subclass, it will then search in the parent class; 2. If other methods are called in this method, the method will still be searched in the subclass and then the parent class in the same order as before.

What is the method for java subclass to call parent class?

[Related learning recommendations: java basic tutorial]

How a java subclass calls the parent class :

When a class inherits from another class and there are no methods of the parent class in the subclass. When calling a method using an object of a subclass, it will first be searched in the subclass. If the method has not been changed in the subclass, it will then be searched in the parent class.

When a method is only defined in the parent class, the properties in the parent class will be used when the method is called.

If other methods are called in this method, it will still be searched in the subclass first, and then in the parent class according to the previous order.

package Temp;
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) {
        A num1 = new A(10);
        B num2 = new B(9);
        num1.show();
        num2.show();
    }
}

The result is:

x=10
y=2
z=5
x=9
y=2
z=8

Related recommendations: Programming video course

The above is the detailed content of What is the method for java subclass to call parent class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn