What is the default method in java?

I don't know how coding works in java. Because of my job, I have to learn some Java code. And something confused me. It seems we can have multiple classes for one project, but there is only one main function (public static void main ()) for the project, and when the program starts, the compiler looks for that main function first.

I have this code:

First.java

class First {
    public static void main(String args[]) {
        SecondClass example = new Second();
    }
}

      

Second.java

class Second {
    method1() {}
    method2(){}
}

      

So now, when the class is run Second

, which method is executed first? As in php, the function index()

runs at the beginning by default.

Guys, I might have sounded really stupid in places and I'm sorry about that.
+3


source to share


5 answers


The method called / called in main method

will be executed first. For example, if you call first method1()

, it will be executed first, and so on ...

Below I provide you with an example that can help you.



HelloWorld.java

public class HelloWorld{

    public static void main(String[] args){

    Hello he = new Hello();
    he.sayHelloToMe(); // if you replace this line by he.sayHelloToYou(); then this method will execute at the first place
    he.sayHelloToYou();
    }
}

class Hello{

    public void sayHelloToMe()
    {
        System.out.println("Hello to me!");
    }

    public void sayHelloToYou()
    {
        System.out.println("Hello to you!");
    }
 }

      

+4


source


It just creates a new object of type Second, but doesn't run any methods.



+3


source


There is Second

no constructor in your class . Otherwise it would execute on instantiation Second

. Your methods Second

will not be executed. You need to write something like example.method1()

.

+3


source


As everyone is saying now, SecondClass

it doesn't actually do anything. From PHP's point of view, the method index()

you are referring to will be a method main

in the class First

. This is your entry point for a program, much like the entry point for your site using PHP. The class is Second

more like another web page that doesn't actually do anything until you call it. I would highly recommend a developer to study the code, although it seems like you are outside your element and might do more harm to your code than help. Your best fortune is to do what you need to do, though.

+3


source


In the first image, you (or tried) to create a second class object. This is the first step to call your methods in the second class. The right way:

Second example = new Second();

      

After you have created an object, you can call the methods of that object. For example, here you can call two methods using

example.method1();
example.method2();

      

The order of the methods executed will depend on the order you call the methods.

Hope this helps. :)

+2


source







All Articles