Skip to content
Advertisement

How to create an object of subclass in java?

I am trying to create an object of subclass which is not static in the main, but not able to do. Does anyone tried the same?

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

}

Advertisement

Answer

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

or in your case

Subclass instance = obj.new SubClass();

You need the instance of the parent class to create instance of inner non-static class.

Advertisement