Sobes.tech
Junior — Middle

Is it permissible to declare a public method inside a class constructor?

sobes.tech AI

Answer from AI

In Java, you cannot declare methods inside a class constructor. A constructor is a special method used for initializing an object, and inside its body, you can only write instructions, not declare new methods. All class methods are declared at the class level, not inside other methods or constructors.

Example of incorrect code (you should not do this):

public class MyClass {
    public MyClass() {
        public void myMethod() {  // Compilation error
            System.out.println("Hello");
        }
    }
}

The correct way is to declare the method at the class level:

public class MyClass {
    public MyClass() {
        // initialization
    }

    public void myMethod() {
        System.out.println("Hello");
    }
}