2013-11-27 69 views
2

我想創建一個子類的對象,它不是主要的靜態,但不能做到。有人嘗試過嗎?如何在java中創建子類的對象?

package com.example; 

import com.example.SubClassExample.MainClass.SubClass; 

public class SubClassExample { 

    static class MainClass { 
     public int mca; 
     protected int mcb; 
     private int mcc; 

     SubClass sc = new SubClass(); 

     public class SubClass { 
      public int sca; 
      protected int scb; 
      private int scc; 

      void method() { 
       mca = 10; 
       mcb = 20; 
       mcc = 30; 

       sca = 10; 
       scb = 20; 
       scc = 30; 

       System.out.println("Subclass: " + mca + " " + mcb + " " + mcc + " "); 
       System.out.println("Subclass: " + sca + " " + scb + " " + scc + " "); 
      } 

     } 

     void method() { 
      mca = 100; 
      mcb = 200; 
      mcc = 300; 

      sc.sca = 100; 
      sc.scb = 200; 
      sc.scc = 300; 

      System.out.println("MainClass: " + mca + " " + mcb + " " + mcc + " "); 
      System.out.println("MainClass: " + sc.sca + " " + sc.scb + " " + sc.scc + " "); 
     } 
    } 

    public static void main(String[] args) { 

     MainClass obj = new MainClass(); 
     obj.method(); 
     obj.sc.method(); 

     SubClass obj1 = new obj.SubClass(); //Getting ERROR here, tried so many like 
        //MainClass.clas.SubClass, obj.class.SubClass, Subclass() but still not able 
        //to do. As it is a public subclass, cant we able to create an object of 
        //that class 
     obj1.method(); 
    } 

} 

回答

2
Subclass instance = new MainClass().new SubClass(); 

或在您的情況

Subclass instance = obj.new SubClass(); 

您需要的父類的實例來創建內部非靜態類的實例。

+0

在上面的代碼中obj已經是MainClass()的實例,但仍然無法做到,任何原因? – Suman

+0

謝謝了吧:),SubClass obj1 = obj.new SubClass(); – Suman

+0

沒問題。樂意效勞 –

1
SubClass obj1 = new obj.SubClass(); //Getting ERROR here, tried so many like 

你不能把一個newobj前:實例MyClass。它實際上沒有意義。這是因爲內部類的對象靜靜地連接到外部類的對象。聲明obj.new InnerClass()具有與obj.innerInstance相同的等同含義:通過外部類的實例引用新的內部實例。

這就是爲什麼,這條線應該是:SubClass obj1 = obj.new SubClass();

1

由於​​也不是一成不變的,所以你需要創建新的實例。

MainClass obj = new MainClass(); 
SubClass obj1 = obj.new SubClass();