How does actually 2 classes work in one program? - java

I probably have quite a big misconception, and I've been looking around the internet and still cant find the answer to my question.
So in java OOP, suppose I have 2 classes one called Main.java, the other Something.java, and because each classes both have their own entry point in their main method.
which one should I start the program with (like to call all the
other classes in that program)?
And, if I were to use Main.java class, how do I call the whole things happening in Something.java? Like if that class was made to do its whole thing, with its own method, variables and all, and I'm just calling it all in the Main.java?
It's quite easy to understand theoretically, but in a program, not so much for me for some reason.

Well it's you who have to decide your entrypoint class. If you decide Main to be entry point class your other main method will treated as normal method like other methods. Hence, you can call that in entrypoint class.
Example below:
public class MultipleMain {
public static void main(String[] args) {
System.out.println("Hello World!!!! I must be executing");
AnotherWithMain.main(new String[]{});
}
}
class AnotherWithMain {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
If you call MultipleMain class i.e. java MultipleMain then output would be:
Hello World!!!! I must be executing
Hello World
and if you call AnotherWithMain then Hello World will be printed per above impl.

One program must have one main method to start with. Because if you ran two main method using java Your_Class then you have 2 jvm instance.
look into some tutorial how to use multiple classes in one program .
Using multiple classes in a Java program
Generally your main class will use other classes instance and static method. see the above simple example.

Related

Method in class vs method under main method

So I have already found this question but I'm having a hard time understanding the answers so sorry that this is a repeat question but when should you use a method written in a class vs a method written under the main method. If you're making a method should't you just put it in a class or are there benefits to writing a method under the main method?
public class MyProgram
{
public static void main(String[] args)
{
method();
classMethod.method2();
}
public static void method(){
System.out.println("Method under main method");
}
}
public class classMethod{
public static void method2(){
System.out.println("Method from class");
}
}
Output:
Method under main method
Method from class
They do the same thing is there a time I should use one way over the other?
I'm goin to assume that for under main method you are referring to create the method on the main class or file.
In java like any other language you can make what ever you want using only the main class but that isn't good, is going to create a really big file and is going to be really hard to maintain.
You use classes in all language to make your program more organize and easy to understand.
(If we dive into really complex program create classes, interface, etc has a lot more reasons that just organize the code, but stick with the basic)
When you need to create a class to hold methods?
That depends on you, and how you want to organize your code.
Its you are really new on Java I recommend to read a little bit on OOP, maybe give you some hints on when you have to use a class or not used.

Can one force execution of the static blocks of all the files in the application?

My goal is to have several classes to have a block of code that runs at the beginning of the program. Assume for a second that classes can be added to the project on a whim, and it will be impractical to have a static function that is called in the beginning of main.
I have tried to place the initialisation routine within the static block of those classes, and it works almost as expected, but not quite. These blocks get called only after something else in that class gets called. This can be demonstrated by the code below:
Test.java
public class Test
{
public static void main(String[] args)
{
System.out.println("Begin");
new Another();
}
}
Another.java
public class Another
{
static
{
System.out.println("Another.static{}");
}
public Another()
{
System.out.println("Another.Another()");
}
}
Another2.java
public class Another2
{
static
{
System.out.println("Another2.static{}");
}
public Another2()
{
System.out.println("Another2.Another2()");
}
}
The output is:
Begin
Another.static{}
Another.Another()
It can be seen that Another2 is assumed not to be there at all.
The question is: Is it possible to "kick" all the classes to execute their static blocks if they have them?
Static blocks are executed if the class is loaded by the ClassLoader. So if you iterate over all your classes and load them via a class loader (no need to instantiate them!) every static block would get executed once.
On a deeper level I can't imagine a situation where you'd actually need this. This somehow hints to misdesigned class structures.
This is not possible, since the VM will never attempt to load a class that isn't required by the code path traversed on its own. There are some obvious and some obscure reasons why its done that way.
Rule of thumb is: If there is no dependency to a class that is reachable (through code) from the programs entry point, then that class will never be loaded. Although reachable is quite lose, e.g. a reference can be established by just knowing a class' name (e.g. from a configuration file) and accessing that class with e.g. Class.forName().
What you cannot achieve is just dropping a class into the class path and have that class automagically become an additional entry point (which executing any static code without a cause from the main (and only) entry point would classify as).
Simply you can't. Static block only called when the class loader loads them for the first time into it. No other way around to call them.
It doesn't make sense to load all keep with you to use them later. Anyways, it will be executed when you use it.

Java Entry Point

Is is possible to change entry point of java program from main(default) to other?
If I write code
public class TestWithoutMain {
static {
System.out.println("hello bristy!!!");
}
}
I am not able to run code in eclipse. If i add main method to above code
public class TestWithoutMain {
static {
System.out.println("hello bristy!!!");
}
public static void main(String[] args) {
}
}
It is printing hello bristy!!!.
The basic concept is the main class is searched first and than and only than it is executed via main. So the first answer is NO. You cannot change the entry point.
Now in your code you have a static System.out.prinln block. In java, static contents are loaded when the class is loaded for the first time and they just have a single copy in the memory. So static block will be executed after the main block is found. Just try removing this main block and you will see the difference yourself
Tricks like putting business code in static initializers (leaving main empty) are possible. But the primary purpose of static initializers is to perform some initializations, not running business code.
You may put something like System.out.println("TestWithoutMain class loaded"); for logging purposes, but this should not be the primary goal of your program.
Java does not prevent you from writing bad, unreadable and unmaintainable code. And from creating nonsense programs. Neither do other programming languages.
Common programming practice discourages you from putting business code in static initializers bypassing main.

Java Understanding Java main method on logic

The main method is the most significant method in your Java application with regards to launching your application as the entry point. What happens prior to this method being used is unclear. Please can someone help me understand/clarify what happens before the method is used by correcting my perception thereof based on the method signature as follows:
The JVM creates at least one Object that will access your main method. This (assumed) object attempts to access your Java application according to the API which obviously binds you to the known method signature public static void main (String[] args){}
public You can't restrict the (assumed) solitary object on the JVM from accessing your Object housing the main method completely looking at logic alone and not the API/signature?
static There are simply no objects up and running to create any other instances of objects up yet (other than the assumed JVM one) to instantiate or create objects out of yet. The static modifier implies the only possibility of accessing this method as it is not bound to an instance and can be accessed therefore 2ithout an instance. Yet again this is logic as without any objects up and running (apart from the assumed JVM one), there can't be any objects up yet to instantiate any other objects with?
args A standard across languages and applications/executables to provide ability to customize the application?|
Is this a correct and logical way to approach and understand the main method?
It's not entirely clear what you're really asking, but the JVM specification section 5.2 covers at least some of this:
The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (ยง5.3.1). The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java Virtual Machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.
In an implementation of the Java Virtual Machine, the initial class could be provided as a command line argument. Alternatively, the implementation could provide an initial class that sets up a class loader which in turn loads an application. Other choices of the initial class are possible so long as they are consistent with the specification given in the previous paragraph.
The JLS section 12.1 has some other descriptions too.
The JVM invokes the main method directly - it doesn't need to create a new object to do so. Although the main method itself has to be public, the class it's declared in doesn't. For example:
public class Test {
private static class EntryPoint {
public static void main(String[] args) {
System.out.println("Hi");
}
}
}
Then execute with:
java 'Test$EntryPoint'
It prints "Hi" as expected.
No code outside the Test class has access to EntryPoint.main() other than through privileged reflection - or direct access that the JVM is clearly capable of.
java first boots up its core - java.lang, classloaders, system properties, runtime etc and then looks at what it has to do. Before the JVM is initialized there is no "java" in that process. Its just a native process and so I think it would be wrong to think in Java terms before this happens.
Now the JVM launcher would first look at pre mains, call them in order (first calling respective static blocks) then look at the main method, call that classes static block(s) if there are any; finally call the main method, passing any command line arguments to the premain and main methods.
Simple Tests:
public class Test {
static{
System.out.println("Hi static 1");
}
public static void main(String[] args) {
System.out.println("Hi main");
}
static{
System.out.println("Hi static 2 better to have 1 static block per class but you can have N ");
}
}
When you put the command like java someClassName then the flowing thing happen.
1.It load the class someClassName and execute the static block(if any)
During class loading an Object class Class will be created which will represent your class.
2.It invoke the main method using the the class name(It won't create any object of your class)
that why main method is static.
Say, file Demo.java contains source code as
public class Demo{
}
when this code is compiled as it's compile successfully as
$javac Demo.java
but when it's executed as
$java Demo
then it shows an exceptional error
Main method not found in class Demo, please define the main method as: public static void main(String[] args)
so compiler is not responsible to check whether main() method is present or not. JVM is responsible for it. JVM check for main() method with prottoype as
public static void main(Strings[] args)
Why JVM search main() method? Is it possible to change main() method into any other method main_hero()?
JVM is instructed to find main() method from inside JVM. Yes, it's possible to change main() method into main_hero() method but inside JVM you must have to instruct to search main_hero() method.
JVM{
public static void main(String[] args)
}
to
JVM{
public static void main_hero(String[] args)
}
Why public?
JVM is installed either in C or D drive so to call from anywhere public is used.
Why static?
main() method is no related to object so without existing object also JVM has to call this method. main method no way related to object.
Why void?
JVM is going to call main() method but what can JVM do with return value if main() method return. So it's meant to be void.

Should I put main method in superclass or subclass in Java

If a class has inheritance in a Java program, do I need to put main method in the superclass or subclass? Many programs put the main method in different positions. Can anybody tell me how to do that? Thanks a lot!
I think it might be best to have a simple class whose sole dedicated purpose is to contain the static main method. It simple and clear.
Your main method would then get things started by creating the initial objects from your program.
You could create a new dedicated class, let's say Launcher, with a main method, instantiate your classes there, and manage any unexpected exceptions:
public class Luncher{
public static void main(String args){
//insert argument checking logic
try{
new MyClass.executeLogic(someArguments);
}catch(Exception e){
//insert exception handling logic here
}
}
It's up to you where you'll put main method, but I'd just put it into new class with only one method, static Main(String[] args)
You would want to put a main() method in a place where you control, or drive all of the action of your program.
Well, it depends, But usually main method put in sub class. There is quite big difference between in inheritance and shadowing. But you can put it subclass or super class. Remember main method is static.
We have to put the main method inside the main class only. Then whether you make it a parent class or sub class doesn't matter, It will work fine, But the main method needs to be inside the main class else compiler will throw error.

Categories

Resources