小编Kir*_*ill的帖子

Java` this`在继承情况下实际指的是什么?

为什么以下Java代码会产生:

10
superclass
Run Code Online (Sandbox Code Playgroud)

有问题的代码是:

class SuperClass {
    int a;

    public SuperClass() {
        this.a = 10;
    }

    private void another_print() {
        System.out.println("superclass");
    }

    public void print() {
        System.out.println(this.a);
        this.another_print();
    }
}

class SubClass extends SuperClass {
    int a;

    public SubClass() {
        this.a = 20;
    }

    private void another_print() {
        System.out.println("subclass");
    }

    public void print() {
        super.print();
    }
}

public class Main {
    public static void main (String[] args) {
        SubClass c = new SubClass();
        c.print();
    }
}
Run Code Online (Sandbox Code Playgroud)

没有SuperClass创造过的实例,不存在吗?不仅Java开始寻找从中调用的方法SuperClass …

java oop inheritance constructor this

8
推荐指数
2
解决办法
371
查看次数

标签 统计

constructor ×1

inheritance ×1

java ×1

oop ×1

this ×1