Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an object of subclass in java?

Tags:

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

}
like image 766
Suman Avatar asked Mar 21 '23 12:03

Suman


2 Answers

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.

like image 55
Narendra Pathai Avatar answered Apr 01 '23 06:04

Narendra Pathai


As SubClass is not static so you need to create new instance.

MainClass obj = new MainClass();
SubClass obj1 = obj.new SubClass();
like image 21
Masudul Avatar answered Apr 01 '23 06:04

Masudul