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