【问题标题】:How to access the subclass's Instance variable using the Array of Object? [duplicate]如何使用对象数组访问子类的实例变量? [复制]
【发布时间】:2016-11-21 09:00:27
【问题描述】:

我想使用对象数组“arr”访问变量“s”?请参考代码sn-p。

    public class Array_Chp3 {
        public static void main(String[] args) {
        Array_Chp3[] arr = new Array_Chp3[3];
        arr[0] = new str();  // when used this line instead of the below line , getting the error "s cannot be resolved or is not a field"
        //arr[0] = new Array_Chp3(); // when used this line instead of the above line, getting the error s cannot be resolved or is not a field
        str obj = new str(); 
        System.out.println(arr[0]);
        System.out.println(arr.length);
        System.out.println(arr[0].s); // How to access the variable 's'?

        }
    }
    class str extends Array_Chp3{
         public String s = "string123 @ str"; 
    }

错误信息: 线程“main”java.lang.Error 中的异常:未解决的编译问题: s 无法解析或不是字段 在 Array_Chp3.main(Array_Chp3.java:17)

【问题讨论】:

  • 你需要一个在str类中的getter,它会返回s。然后你可以把它叫做arr[].getS();
  • 您没有显示您的 str 类的代码(顺便说一句,应该以大写首字母命名,Str)。它是否有一个可以从那里访问的字段s
  • @SantiBailors 是的,他确实显示了str 的代码。阅读问题。
  • @JBNizet 对,我错过了,我很抱歉。

标签: java inheritance arrayobject


【解决方案1】:

您的数组是 Array_Chp3 的数组。这意味着您决定此数组的元素是 Array_Chp3 的实例。你并不关心它们有什么具体类型,只要它们是 Array_Chp3 的实例即可。

您在其第一个元素中存储的是str 实例。没关系,因为 str Array_Chp3(它扩展了 Array_Chp3)。

但是由于数组的类型是Array_Chp3[],编译器不能保证它的元素都是str的实例。它只能保证它们是 Array_Chp3 的实例。

你知道它是一个str,所以你可以告诉编译器:相信我,我知道它实际上是一个str。这称为演员表:

System.out.println(((str) arr[0]).s);

但它显示了一个设计问题。如果您需要元素是str 的实例,则该数组应声明为str 的数组。

【讨论】:

  • 非常感谢.. 成功了。
【解决方案2】:

如果你知道它是 str,你可以这样转换:

System.out.println(((str)arr[0]).s);

【讨论】:

  • 这不应该工作。如果您阅读错误消息,您就会明白为什么
  • 我几乎可以肯定这会起作用 ;)
  • @XtremeBaumer 是的,它会的。而且你关于吸气剂的建议是完全错误的。
  • 谢谢@JB Nizet
猜你喜欢
  • 2016-09-15
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 2021-04-21
相关资源
最近更新 更多