代码之家  ›  专栏  ›  技术社区  ›  Alan

`试图访问子类的属性时找不到符号',但变量的类型为超类

  •  0
  • Alan  · 技术社区  · 7 年前

    JavaNoB这里,我有一个OuttoStand类型的变量,在函数中,我有一个条件,当我尝试访问属于任何子类的任何属性时,我要么将OutPoSt流分配给FieleOutToStudio或BytErayOutPutsFipe的新实例。我得到了 Error cannot find symbol . 有没有一种方法可以保持同一父类的变量,并尝试告诉运行时,每当我需要访问属性时,它都是子类类型的?

    这是一些伪代码

    public void work(Map params)
    {
    OutputStream output = null;
    
    
    if(params.isAFile)
    {
      output = new FileOutputStream();
    }
    else
    {
      output = new ByteArrayOutputStream();
    }
    
    ...do some work that makes use of the OutputStreams class
    if(isFile)
    {
      return output
    }
    else
    {
      mybuffer = output.buf; //it fails here with Cannot find symbol since output is of type OutputStream when it should be treated as type ByteArrayOutputStream
      return myBuffer;
    }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Josh    7 年前

    你必须这样做:

    (ByteArrayOutputStream output).buf
    

    Java不知道它可以安全地调用ByteArrayOutputStream中的方法,因为OuttoSt流不具有该方法。