是指“ this”子类,而不是Java中的“ this”超类?

问题描述 投票:0回答:1

我为我当前的一个Java项目构造了一个超类和一批子类-在这种情况下,我想在超类中定义一个函数,以供所有子类继承。此函数将使用“ this”来引用子类中的属性,但是当前它引用了SUPERclasss中的属性。

F.e。,我创建了一个超类和一个子类,其中两个类都具有“值”属性。一个函数用于打印该值,其中“ this”应指代当前类。

public class Main{
    public static void main(String[] args) {
        Child myObject = new Child();
        myObject.printValue();
    }
}

class Parent{
    private int value = 10;
    public void printValue(){
        System.out.println(this.value);
    }
}

class Child extends Parent{
    private int value = 20;
}

在这种情况下,我想通过使用“ this”来引用当前类来确定子类(20)中的值。但是,“ this”当前是指SUPER类中的“ value”,从而为所有子类产生相同的打印消息。

我可以设置“ this”来引用使用该函数的类吗?

java oop this
1个回答
0
投票

这不起作用,因为不能在子类中“覆盖”字段。只有方法可以被覆盖。

[如果创建getValue方法,您将获得想要的效果,将this.value替换为对getValue的调用。

class Parent{
    private int value = 10;
    public void printValue(){
        System.out.println(getValue());
    }
    protected int getValue() {
        return value;
    }
}

class Child extends Parent{
    private int value = 20;

    @Override
    protected int getValue() {
        return value;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.