Java抽象类字段覆盖 [英] Java abstract class fields override

查看:35
本文介绍了Java抽象类字段覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类应该实现一个公共字段,这个字段是一个接口或另一个抽象类.

I have an abstract class that should implement a public field, this field is an interface or another abstract classe.

像这样:

public abstract class GenericContainer {
    public GenericChild child;
}

public abstract class GenericChild {
    public int prop1=1;
}

public abstract class SpecialChild extends GenericChild {
    public int prop1=2;
}

现在我有另一个专门的类容器:

Now i have another specialized class Container:

public abstract class SpecialContainer extends GenericContainer {
    public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
}

Java 允许我编译它,我想象 SpecialContainer 中的字段 child 自动重载 child 的字段>GenericContainer...问题是:我是对的吗?孩子的自动超载"会发生吗?

Java allow me to compile this, and i IMAGINE that the field child in SpecialContainer is automatically overloading the field child of the GenericContainer... The questions are: Am i right on this? The automatic 'overloading' of child will happen?

而且,更重要的问题,如果我有另一个这样的类:

And, more important question, if i have another class like this:

public class ExternalClass {
    public GenericContainer container=new SpecialContainer();
    public int test() {
         return container.child.prop1
    }
}

test() 会返回 1 还是 2?我的意思是 GenericContainer 容器字段 prop1 将调用什么,是通用的还是特殊的?如果特殊的 prop1 被声明为 String(是的,在这种情况下,java 也允许我编译)怎么办?

test() will return 1 or 2? i mean the GenericContainer container field what prop1 will call, the generic or the special? And what if the special prop1 was declared as String (yes java allow me to compile also in this case)?

谢谢!

推荐答案

它不会覆盖任何内容,您只是在当前类范围内隐藏原始字段.如果您使用具有子类型的变量,您仍然可以访问原始属性.示例:

It isn't overriding anything, you're just hiding the original field at the current class scope. If you use a variable with the subtype you will still be able to access the original property. Example:

abstract class GenericContainer {
    public GenericChild child;       
}

abstract class GenericChild {
    public int prop1=1 ;
}

class SpecialChild extends GenericChild {
    public int prop1=2;
}

class SpecialContainer extends GenericContainer {
    public SpecialChild child;
}

public class Main {

    public static void main( String ... args ) {

        GenericContainer container = new SpecialContainer();
        container.child = new SpecialChild();

        System.out.println( container.child.prop1 );

        SpecialChild child = (SpecialChild) container.child;        
        System.out.println( child.prop1 );
    }

}

这将打印 1,然后打印 2.

This prints 1 and then 2.

SpecialChild 您还可以使用 super 上升一级:

From SpecialChild you would also be able to go up one level using super:

class SpecialChild extends GenericChild {
    public int prop1=2;

    public int getOriginalProp1() {
        return super.prop1;
    }

}

这篇关于Java抽象类字段覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆