About methods and to create another method

There are a few issues with this code. I have made a revised version of it, with comments to help you understand why it would not work.

public class Main {
    //There is no reason to use public, final, or static on this int variable
    int a = 10;
    public static void main(String[] args) {
        //Cannot print a, as main is a static method and a is out of it's scope
        //System.out.println(a);

        //Creates new "Main" object, calls hai method
        Main m = new Main();
        m.hai();
    }

    public void hai() {
        int b = 1;
        System.out.println(b);
    }
}

When we create the “Main” object, we are creating an instance of this class. An instance is simply an Object created from a class. In this example that object is Main. Once this instance is created, we are able to call all of the methods located inside Main, (including the ‘hai’ method)

Also, ensure your Main class surrounds all of your methods.
Your class contains all of the methods needed to perform your file’s functions. You will not have two classes inside one file, nor will you write much outside of the class declaration, (excluding imports, etc).

Browse More Popular Posts

Leave a Comment