无法找到特定代码行显示错误的原因

时间:2014-12-10 10:38:49

标签: java object reference

package morepackage;

public class Exampleclass {

String s = "myname";

public static void main( )

{

    Object [] a = new Object[10];

    a[1] = new Exampleclass();

    System.out.println( a[1] );//this is working

    System.out.println( a[1].s);//**this is not working**

    Exampleclass t = new Exampleclass();

    System.out.println(t);//this is working

    System.out.println(t.s);//this is working
}

}

代码中的某些上述行正在运行,而其他行则不是任何人都可以

解释为什么行 “System.out.println(a [1] .s);” 显示错误。

4 个答案:

答案 0 :(得分:1)

如果是System.out.println(t.s);,则正在访问和打印s的{​​{1}}属性t。但是Exampleclassa[1],没有这样的属性。

答案 1 :(得分:1)

替换

System.out.println( a[1].s);

System.out.println( ((Exampleclass)a[1]).s);

aObjects的数组,因此您需要将其元素强制转换为Exampleclass,然后才能使用Exampleclass中定义的任何方法或属性。

答案 2 :(得分:0)

package morepackage;

public class Exampleclass 
{

  String s = "myname";

  public static void main( )

  {

    // array of objects
    Object [] a = new Object[10];

    a[1] = new Exampleclass();

    // prints an object not an instance Exampleclass class
    System.out.println( a[1] );//this is working

    // System.out.println( a[1].s);//**this is not working**

    Exampleclass temp = (Exampleclass) a[1];

    System.out.println( temp.s)


    Exampleclass t = new Exampleclass();

    System.out.println(t);//this is working

    System.out.println(t.s);//this is working
  }

}

答案 3 :(得分:-3)

尝试投射[1],目的是访问s属性,如

System.out.println( ((Exampleclass)a[1]).s);