E.g: I got a Java class with the main function implemented like this:
public class Job{
public static void main(String[] args) throws Exception{
Job jobA = new Job();
String jobName = System.getProperty("JobName");
job.DoJobA("jobName");
}
public void DoJobA(String jobName){
String configPath = System.getProperty("ConFig");
File file = new File(configPath+ "/" + jobName);
DoJobB(file);
}
}
And I another class and want to call the main function of class Job but couldn't find a way to do that!
Is there any advise for me?
You should be able to call it like you call any other static method
Job.main(yourArgs);
If you make the main method use var args then you dont need to pass in any variable
public static void main(String... args) throws Exception{
...
}
then you can just call it as
Job.main();
if you need arguments then you can pass them if.
Related
I am trying to learn how constructors work and I have been trying to debug this simple java program but I cannot get it to run. Eclipse simple refuses to acknowledge its presence and just runs an earlier project. Any ideas would be very gratefully received - I am struggling to see what I have done wrong.
package timber;
public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
public Person(String personFirstName, String personLastName, String personAddress, String personUsername)
{
firstName = personFirstName;
lastName = personLastName;
address = personAddress;
username = personUsername;
}
public void displayPersonDetails()
{
System.out.println("Name: " + firstName + " " + lastName);
System.out.println("Address: " + address);
System.out.println("Username: " + username);
}
}
I then have a second class that contains the main method
package timber;
public class PersonExample {
public void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
}
could you please add static in main method :-
public static void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
Your main method always needs to be static.
See Why is the Java main method static?
Replace,
public void main(String[] args)
with
public static void main(String[] args)
Your main method needs to be 'static'. Why? If you want to call a method in Java, there are two ways
Create an instance of class and use that object to call it's methods
Make a method 'static' so that you can call the method using the class name and no instance creation needed.
The 'main' method, if non-static (like in your case) you have to create an instance of it's class to call. But, where would you create an instance of that class, where your main method is residing? Create another class and call from there? and create yet another class to call this class? It will never end. I mean there has to be a starting point right?
By giving the method the name 'main' and by adding the keyword 'static' in it's signature, you help JVM call that method without the need to an create instance.
Just change
public void main(String[] args)
to
public static void main(String[] args)
Everything is fine you have just missed the static keyword .
Instead of
public void main(String [] args)
Use
public static void main(String[] args)
I have an abstract class called Trader which acts like a client with a server (StockMarket) and I would like to declare in the Trader class that all classes that inherit from it will need to implement a main entry point so that they can be run.
The problem is that if I write:
public static abstract void main(String[] args) throws Exception;
it gives an error that only visibility modifiers are allowed. But if I remove the static modifier then it does not work as a main entry point allowing it to be run.
So how to declare all subclasses of an abstract class must implement a main method?
You can't.
What I would do instead is declare an abstract, non-static method in Trader:
public abstract void run(String[] args) throws Exception;
And then declare a separate main class that would instantiate an instance, and call the run method:
class RunTrader {
private static final String DEFAULT_CLASS = "...";
public static void main(String[] args) {
try {
String className = System.getProperty("main-trader-class", DEFAULT_CLASS);
Class<Trader> traderClass = (Class<Trader>)Class.forName(className);
Trader trader = traderClass.newInstance();
trader.run(args);
} catch (Exception e) {
// handle the exception
}
}
}
Lets start with the meaning of
public static void main (String[] args)...
static
means that this method does require an instance of the class (containing this method). Java virtual machine (JVM) states this as a requirement for the entry point of a program, reason being that the class may have multiple constructors or no default constructor and there is no way for JVM to know how to create object of the class.
public
allows the method to be accessible outside the package (and class obviously), so JVM is free to invoke this method.
main
is the name of the method that JVM looks for in the class, since there could be multiple public static methods.
void
returns nothing. This is the part of the signature that JVM looks for as entry point.
Now lets answer your question in light of this information. Polymorphism is relevant to OOP concept of inheritance and interface implementation, and it irrelevant to static methods.
So the only choice you have is to choose 1 'public static void main' method as the entry point based on the 'args', call other public static methods. However, other methods need not have the same signature.
Static methods cannot be abstract.
Static members data are same for all the objects and derived classes.
Static members can't be overridden by derived class.
Since abstract method need to be defined in derived class it can't be static.
Remove static and try.
static method does not supports polymorphism, so you can't declare it as abstract. but you can declaring an abstract class with abstract methods that #MauricePerry has been proposed. I will come up with how to get the Main class?
you can extract the Main class name from the system property sun.java.command.
truncate the args from the command.
second, truncate the IDE Main class name if present.
here is my implementation you can using:
public abstract class Trader {
protected abstract void run(String... args);
public static void main(String[] args) throws Exception {
runAs(getMainClass(args)).run(args);
}
private static Trader runAs(Class<?> mainClass)
throws IllegalAccessException, InstantiationException {
checking(!Modifier.isAbstract(mainClass.getModifiers())
, () -> "abstract class can't be run: " + mainClass);
checking(Trader.class.isAssignableFrom(mainClass)
, () -> "class is not a " + Trader.class
+ " can't be run: " + mainClass);
return Trader.class.cast(mainClass.newInstance());
}
private static void checking(boolean condition, Supplier<String> message) {
if (!condition) {
throw new IllegalArgumentException(message.get());
}
}
private static Class<?> getMainClass(String... args)
throws ClassNotFoundException {
String command = commandWithoutArgs(args);
String[] classes = command.split("\\s+");
return Class.forName(classes[ classes.length - 1]);
}
private static String commandWithoutArgs(String[] args) {
String command = System.getProperty("sun.java.command");
return command.substring(0, command.length() - argsLength(args)).trim();
}
private static int argsLength(String[] args) {
if (args.length == 0) {
return 0;
}
return Stream.of(args).collect(Collectors.joining(" ")).length() + 1;
}
}
Example
public class Application extends Trader {
#Override
protected void run(String... args) {
System.out.println("Application");
}
}
run the Application using command java Application or run it in IDE.
To run a program JVM find main method like
public static void main(String[] args)
abstract is not used with main method
Hi friends im learning java from basics..
I have some doubt in implementing interface.
WORKING CODE
Using interface in a class is working....
interface bala
{
void prnt();
}
class ex implements bala{
#Override
public void prnt() {
System.out.print("hi");
}
}
public class Solution
{
public static void main(String arg[])
{
ex p = new ex();
p.prnt();
}
}
NOT WORKING
Here is my doubt, why i cant implement interface in main method?
plea
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
prnt();
}
#Override
public void prnt() {
System.out.println("hi");
}
}
What is happening here?
Why implementing on main() is not working?
Is there is a way to make working interface on main function?
Given Bellow code works well.
interface bala
{
void prnt();
}
public class Solution implements bala
{
public static void main(String arg[])
{
Solution sol = new Solution();
sol.prnt();
}
public void prnt() {
System.out.println("hi");
}
}
It's not working, because you're trying to access non-static (i.e. instance) method from a static context.
In order to invoke it, you need an instance of the Solution class (note that in your working code you have an instance of the ex class, so here you need to do the same with slight difference):
Solution instance = new Solution();
instance.prnt();
Problem is main() is static, static blocks can access static members or with object reference . So here you could simply create an object/instance to invoke the method:
new Solution().prnt();
try new Solution().prnt() instead of calling prnt()
the problem is :
main method is a static method. And your overridden method is non-static. You can't call non-static methods from static context.
In order to call overridden method prnt() to call, you need to instantiate you Solution class like -
Solution sol = new Solution();
and then
sol.prnt();
Best Option to Do it . Create the instance of class and Access it.since main method is a static method you can do like that
Solution instance = new Solution();//Creating instance of class
instance.prnt();//access prnt .
You should create the object of Solution class in main method
Solution s1 = new Solution();
s1.print();
Otherwise, you can create the method as static because you are trying to access
the method from static context.
I forgot a concept that I used and can't remember it.
For the context, I used to have a method like toString() which had a parameter. This parameters allowed me to call my method like myMethod(System.out::println) to print it on the screen, but also to print it in a file with the same syntax.
Does anyone know what can be this parameter? the concept?
I think it's kind of a FunctionalInterface but I don't know what it is.
This is called method reference and applies when you know what method you want to call, provided the method already exist.
From the tutorial :
Because this lambda expression invokes an existing method, you can use
a method reference instead of a lambda expression:
Arrays.sort(rosterAsArray, Person::compareByAge);
Available since Java-8.
An exemple using what you want:
public static void function(String s, Consumer<String> f) {
f.accept(s);
}
public static void main(String args[]) {
String test1 = "test";
String test2 = "test2";
function(test1, System.out::println);
function(test2, System.out::println);
function(test1, System.out::print);
function(test2, System.out::print);
}
This goes well with java 8 functional interface:
#FunctionalInterface
static interface MyPrinter {
public void println(String line);
}
static void myMethod(MyPrinter mp) {
mp.println("Hello wolrd");
}
...
public static void main(String[] args) throws IOException {
myMethod(System.out::println);
PrintWriter pw = new PrintWriter("myFile.txt");
myMethod(pw::println);
pw.close(); //never forget to close file output streams!
//EDIT: note that you can of course store your MyPrinter in a variable:
MyPrinter mp = System.err::println;
myMethod(mp);
}
Would this work for you?
public class C {
static void myMethod(java.io.PrintStream p) {
p.println("Hello!");
}
public static void main(String args[]) {
myMethod(System.out);
}
}
Unfortunately you can't pass System.out.println directly, because in Java methods (before Java 8) are not first-class objects. All you can do with a method is calling it. As a workaround, you can introduce an interface and create an adapter class.
I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
public class Test2 {
String name;
public Test2 (String nm) {
name = nm;
}
}
I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)
The reason you are getting a compilation error, is that in your method
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,
public class Test {
Test2 t;
public static void main(String[] args) {
Test test = new Test();
test.t = new Test2("Joe");
test.displayName();
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.
You may give the reference to your test object as an argument to method displayName:
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println("Name2: " + test.name);
}
}
Note: I also made displayName a static method. From within your main method you can only access static methods without reference.
Modify the Test class to this
public class Test {
private static Test2 t;
public static void main(String[] args) {
t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Use a getter for your purpose. This is a side solution to your problem, but generally this is how you should retrieve instance variables, using getters.
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println(test.getName());
}
}
public class Test2
{
private String name;
public Test2 (String nm)
{
name = nm;
}
public String getName()
{
return name;
}
}
Always remember, variables in your class should be private. That protects it from access from outside the class. Hence, getters are the only way to access them. And setters or constructors to initialize them.
Fewer statics the better I reckon.
I would Instantiate Test and call displayName on the instance of it, then pass the instance of Test2 to displayName.
But it does depend on what the overall aim is