java static method why is needed [duplicate] - java

This question already has answers here:
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 6 years ago.
I'm using eclipse as IDE for java.
I wrote the following code, but I have one error on loadStrade(). Eclipse suggested me to change loadStrade from public void to public static, and I don't understand why?
I've looked for similar problem and I've found some problems like mine, but I still not understand why I have to change method to static. Uffa!
In the code, routesNet is a graph (jgraphT), and loadStrade() is used to populate vertex and edge.
Can I have help. Thanks, Fabrizio
public class GestioneStrade {
private Stradario routesNet;
public static void main(String[] args) {
/*
* Instantiate Stradario and fill it with routes and cross
*
*/
GestioneStrade m = new GestioneStrade(); //istance of gestionestrade ok?
// now I set new routesNet
m.setRoutesNet(new Stradario());
loadStrade(m.getRoutesNet()); // why loadStrade must be static :-(
}
public Stradario getRoutesNet() {
return routesNet;
}
public void setRoutesNet(Stradario routesNet) {
this.routesNet = routesNet;
}
public void loadStrade(Stradario str) {
// some code to fill routesNet
}

In "main" you should replace
loadStrade(m.getRoutesNet());
to
m.loadStrade(m.getRoutesNet());
And leave loadStrade as non-static.

Related

Static method getting called using a null reference [duplicate]

This question already has answers here:
Why I am not getting NullPointerException? [duplicate]
(6 answers)
Closed 6 years ago.
public class Test {
public static void main(String[] args) {
Test test = null;
test.func();
}
static void func(){
System.out.println("Hello!!");
}
}
Why this program is getting executed successfully?
This is because static methods are not related to instances. Compiler internally convert this and call Test.func()
You call a static method. Static methods are invoked on Classes.
The call is like this Test.func().
Tip: In your code when you call static methods. Call them Class.method() not on object.

In a constructor, find which class created the object? [duplicate]

This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 8 years ago.
Here's what I'm trying to do:
In my code, I have sets of classes that create objects of other classes. What I am trying to do is, in the constructor of the class that's constructor gets called, find the class which called the constructor in the first place.
For example:
Main.java:
public class Main {
public static void main(String[] args) {
Test t = new Test();
}
}
Test.java:
public class Test {
public Test(){
//somehow find the class where I came from :(
}
}
Assuming that you can't pass in the Class object of your caller: Other than the fact that the very need for this implies a rather obnoxious design, then, the only way you can do this is to construct an exception and inspecting the last stack trace element in it:
Exception e = new Exception();
StackTraceElement[] elements = e.getStackTrace();
The first element in the array is what you're looking for.
(Updated following a comment) This won't work consistently in JITted environments.
You can use something like this:
public class Main {
public static void main(String[] args) {
new Main().runMe();
}
public void runMe() {
new Test(this.getClass());
}
}
class Test {
public Test(Class clazz) {
System.out.println("I was invoked from '" + clazz.getCanonicalName() + "' class.");
}
}
Prints:
I was invoked from 'Main' class.

Java chained constructor calling error [duplicate]

This question already has answers here:
How do I call one constructor from another in Java?
(22 answers)
Closed 6 years ago.
This made me mad (Eclipse Kepler)
public class FastReader
{
public static void main (String[] args)
{
FastReader a = new FastReader("hi");
}
public FastReader(int a)
{
}
public FastReader(String b)
{
FastReader(10);
}
}
And I get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method FastReader(int) is undefined for the type FastReader
at FastReader.<init>(FastReader.java:14)
at FastReader.main(FastReader.java:6)
It almost made me mad! help me get rid of this!
Thank you!
Use
public FastReader(String b) {
this(10);
}
public FastReader(String b)
{
this(10);
}
This is the correct way to call the same class constructor.
If you want to call a same class constructor use the keyword 'this' if you want call the parent class constructor use the keyword 'super'.

Java Overloaded Constructors [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Understanding which constructor is chosen and why
Why compiler acts like this,
public class Calculator{
private Calculator(Object o) {
// code goes here
}
private Calculator(double[] calc) {
// code goes here
}
public static void main(String[] args) {
new Calculator(null);
}
}
This program executes second constructor. Why first constructor not execute?
Both constructors are accessible and applicable.
The constructor Calculator (Object) accepts any parameter passed to Calculator (double[]), so Calculator (Object) is less specific.

Exception in thread "main" java.lang.NoSuchMethodError: main [duplicate]

This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 9 years ago.
when i try to compile this:
public class Risk
{
}
class territory
{
public static void main (String[]arg)
{
System.out.println ("hi") ;
}
}
I get this error message:
Exception in thread "main" java.lang.NoSuchMethodError: main
whats going wrong here?
The class containing the main() function must be public, and you may only define one public class per file. You'll want to have two separate files Risk.java and Territory.java.
Risk.java:
public class Risk {
}
Territory.java:
public class Territory
{
public static void main (String[]arg)
{
System.out.println ("hi") ;
}
}
EDIT: It turns out this isn't true - I was able to run your initial code with the following command line:
java territory
But my earlier comments point to the best practice for a real app, such as a Risk game.
What class are you trying to run? If you're using the class territory, that will work. Risk has no main method, though.
Can you figure out why this example causes the same issue?
public class Simple {
public void main(String args[]) {
System.out.println("Inside function");
}
}
Answer: because main() should be public static void!
Could it just be a spacing issue? Your original post shows no space between the ']' and 'arg'.
Try this:
public static void main (String[] arg)
or, if that still doesn't work:
public static void main (String arg[])
What the answer wound up being was that the class i run must contain main or else it won't work. i'm posting this because, though other answers give roughly the same information, they don't make it explicit.

Categories

Resources