如何在java中创建子类的对象?

时间:2013-11-27 07:25:27

标签: java

我正在尝试创建一个子类的对象,它在main中不是静态的,但是无法做到。有没人试过呢?

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();
    }

}

3 个答案:

答案 0 :(得分:4)

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

或在你的情况下

Subclass instance = obj.new SubClass();

您需要父类的实例来创建内部非静态类的实例。

答案 1 :(得分: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();

答案 2 :(得分:1)

由于SubClass不是静态的,因此您需要创建新实例。

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