[英]How to instantiate and call methods dynamically of a class member in Java?
[英]How to instantiate an array of a member class in java
我有一個名為MultiplePrintableInvoiceData的類,這個類有一個內部類,它是一個名為Product的成員類。
我可以使用以下代碼在另一個類中實例化Product實例:
MultiplePrintableInvoiceData pid = new MultiplePrintableInvoiceData();
MultiplePrintableInvoiceData.Product product = pid.new Product();
但是當我嘗試使用以下代碼實例化Product數組時:
MultiplePrintableInvoiceData.Product[] product = pid.new Product[];
我收到編譯錯誤:“(”預期 - 表達非法開始。請我幫忙。
更新我已將代碼修改為:
MultiplePrintableInvoiceData.Product[] product = pid.new Product[11];
但它仍然給我一個錯誤!
除非我們已經擁有外部類的對象,否則無法創建內部類的對象。 這是因為內部類的對象安靜地連接到它所構成的外部類的對象。 但是,如果創建嵌套類( 靜態內部類),則不需要對外部類對象的引用。
但是,創建內部類的數組時不是這種情況。 在創建內部類的Array的同時,我們不能使用外部類的Object來引用內部類。 因為,我們沒有創造任何內在的對象。 我們只創建一個數組,它只是放置內部對象的地方。 它不需要屬於任何外部對象。
class Outer
{
class Inner
{
// field declaration and other code
}
}
//...........
Outer outerObj = new Outer();
Outer.Inner innerObj = outerObj.new Inner(); // instance creation of inner class
Outer.Inner[] innrArr = new Outer.Inner[5]; // array creation of inner class
對於您的上下文,您需要:
MultiplePrintableInvoiceData.Product[] product = new MultiplePrintableInvoiceData.Product[10];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.