简体   繁体   English

尝试访问子类的属性时出现“找不到符号”,但变量的类型为超类

[英]`Cannot find symbol` when trying to access a property of a child class but the variable is of type superclass

Java noob here, I have a variable of type OutputStream and later on in the function I have a condition where I either assign OutputStream to a new instance of FileOutputStream or ByteArrayOutputStream, however whenever I try to access any property that belongs to any of the subclasses. Java noob在这里,我有一个OutputStream类型的变量,后来在函数中有一个条件,我将OutputStream分配给FileOutputStream或ByteArrayOutputStream的新实例,但是每当我尝试访问属于任何子类的任何属性时。 I get a Error cannot find symbol . 我收到Error cannot find symbol Is there a way to keep the variable of the same parent class and try to tell the runtime that whenever I need to access the property it would be of the child's class type? 有没有办法保持同一个父类的变量并尝试告诉运行时,只要我需要访问该属性,它将是子类的类型?

Here is some pseudo code 这是一些伪代码

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;
}

}

You have to cast it like this: 您必须像这样强制转换:

(ByteArrayOutputStream output).buf

Java doesn't know that it can safely call the method in ByteArrayOutputStream since OutputStream doesn't have that method. Java不知道它可以安全地在ByteArrayOutputStream中调用该方法,因为OutputStream没有该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM