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.
Related
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.
Most programs I see have main method inside a public class, in contrast to a no-modifier class. eg:
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
rather than
class Main
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
From what I read, the only reason to have the class explicitly public, is to make it visible to classes outside its' own package.
The job of main is merely to act as a plugin to your actual program API that can be easily interchanged with any other class with main with it(GUIs/CUIs change all the time, and must be designed to be disposable).
If I do not intend the class to be visible to other Java classes; and if I need it to be, I can create a new container class for a new main which is aware that it may be used by other classes, and it would be public.
Is there any reason to make container classes for main "public" by default, other than teaching people to name their classes the same way as the class within it(which is not enforced if you omit public, and causes confusion of "why does Foo.java produce Main.class?")?
I think there are 3 reasons why it's usually done this way:
It feels weird to have a public static method in a class that is not public
main classes are rarely exposed in a public API library, so it doesn't really matter. And IDEs generally generate public classes by default.
The bootstrapping code of the VM that must call the main method is seen as code external to the package, and it thus feels right to make the class public to make it accessible to this logically external code.
I don't thing there are technical reasons for this.
Non-technical reasons I can think of are:
Convention. How many people will be surprized to see non-public main class? Any profit from that surprize?
Expression of intention. public means public, no modifier means package-private. I would consider main class to be intended for public usage, so public is a better expression of this intention.
I know this question has been asked before. But I want to understand the difference with the perspective of my code.
So here is the scenario.
I have a class Main.java. This class calls a different class Secondary.java . On a particular method in the Secondary class, I want some values in the Main class to be updated. There are two ways to do this.
1) One way for doing this is through Callback functions in java.
2) Second is if I define a static function in Main class, then call the static function from Secondary Class.
Here are my two approaches.
Approach 1
Interface CallBack.java
public Interface Callback{
public void updateValues();
}
Main.java
public class Main implements Callback {
static int a=1;
public static void main(String args[]) {
Callback callback = new Main();
Secondary obj = new Secondary(callback);
obj.onClick();
}
public void updateValues(){
a = 4;
}
}
Secondary.java
public class Secondary{
private Callback callback;
Secondary (Callback callback) {
this.callback=callback;
}
//On this method click, I want to update values in the Main class
public void onClick(){
callback.updateValues();
}
}
Approach 2
public class Main {
static int a=1;
public static void main(String args[]) {
Second obj = new Second();
obj.onClick();
}
public static void updateValues(){
a = 4;
}
}
public class Secondary{
Secondary () {
//On this method click, I want to update values in the Main class
public void onClick(){
Main.updateValues();
}
}
So I just want to know that which approach is better? When are callback functions really useful?
Note: This is just an example to understand the difference between the two concepts.
Which approach is better? The answer always depends on context, there are cases to break every rule. That said, keeping coupling low and code simple and unit tested are the usual priorities.
static method
pros: simple, and direct
disadvantages: the static method cannot be substituted with
other implementations.
callback approach
pros: easy to substitute callbacks, good for mocking in tests
cons: a little more overhead for the callback (although JVMs
can often optimise them out) and a little more conceptual
cost to developers; which will be low if they are not abused.
Judging by your choice of example, I suspect that you are working on a GUI. With large applications, the static method approach does not tend to scale without becoming brittle to change. So while your application is small, you will find that the static method approach is simple and tempting. However as your application grows, and you add more people to the project who all need to make changes to the growing code base at the same time we need ways to isolate parts of the application and to unit test those parts. This is where the callback approach shines.
The danger with the callback approach is that it becomes over used. Avoid nesting callbacks as much as possible (there are patterns from the functional world that make this a great technique, but perhaps that is for another post) and the callback must not know about the caller. A cyclic dependency tends to complicate code at a non-linear rate.
I would personally prefer Approach 2 from what you described. That leaves me with principle called open for extension and closed for modification.
So tomorrow if i have a new Callback i could inject it directly in it and use updateValue method.
If i have ever to follow the approach one then this means:
I am breaking OOP principle by using static. You would not be able to override static method.
If tomorrow your updateValue needs change you are going to change Main which breaks closed for modification principle
This would close the doors of further reusability as well.
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.
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.