Java抽象类字段重写 [英] Java abstract class fields override

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

问题描述

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

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 extend GenericChild {
    public int prop1=2;
}

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

Now i have another specialized class Container:

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

Java允许我编译这个,我IMAGINE,字段<$ c 中的<$ c> child 会自动重载 $ c> 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(是的,允许我在这种情况下也允许我编译)?

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)?

谢谢! $ b

推荐答案

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

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 ,您还可以使用 code>:

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天全站免登陆