Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

508
Views
How to create an object of a class that lives within a method in Java?

I have following class:

public class SomeClass {
    public static void main(String[] args) {
        //
    }

    private static void test() {
        MyClass myClass = new MyClass(); //Doesn't work
        myClass.print(); //Doesn't work

        class MyClass {
            void print() {
                System.out.println("Some text");
            }
        }
    }
}

How to create an object of type MyClass? Both lines produce compilation error.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You need to declare the class first before being able to use it:

public class SomeClass {
    public static void main(String[] args) {
         test();
    }

    private static void test() {
        class MyClass {
            void print() {
                System.out.println("Some text");
            }
        }

        MyClass myClass = new MyClass();
        myClass.print();
    }
over 4 years ago · Santiago Trujillo Report

0

If you are using Java version before then 11 then you can't define class inside method and you need to try to define it in scope of SomeClass and then access it through the SomeClass:

public class SomeClass {
    public static void main(String[] args) {
        test();
    }

    private static void test() {
        MyClass myClass = new SomeClass().new MyClass(); // Doesn't work
        myClass.print(); // Doesn't work
    }

    class MyClass {
        void print() {
            System.out.println("Some text");
        }
    }
}

However, if you are using Java 11+ you need to change the order of your code inside the test method to define the class first and access it next:

public class SomeClass {
    public static void main(String[] args) {
        test();
    }

    private static void test() {
        class MyClass {
            void print() {
                System.out.println("Some text");
            }
        }
        MyClass myClass = new MyClass(); // Doesn't work
        myClass.print(); // Doesn't work
    }
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!