简体   繁体   中英

`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. I get a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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