我想創建一個子類的對象,它不是主要的靜態,但不能做到。有人嘗試過嗎?如何在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();
}
}
在上面的代碼中obj已經是MainClass()的實例,但仍然無法做到,任何原因? – Suman
謝謝了吧:),SubClass obj1 = obj.new SubClass(); – Suman
沒問題。樂意效勞 –