[英]`Cannot find symbol` when trying to access a property of a child class but the variable is of type superclass
Java noob在這里,我有一個OutputStream類型的變量,后來在函數中有一個條件,我將OutputStream分配給FileOutputStream或ByteArrayOutputStream的新實例,但是每當我嘗試訪問屬於任何子類的任何屬性時。 我收到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;
}
}
您必須像這樣強制轉換:
(ByteArrayOutputStream output).buf
Java不知道它可以安全地在ByteArrayOutputStream中調用該方法,因為OutputStream沒有該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.