Are these two method calls the same? [duplicate] - java

This question already has an answer here:
What are the advantages of an anonymous object?
(1 answer)
Closed 6 years ago.
Code blocks number 1.
public class SomeClass {
public static void main(String [] args) {
SomeClass foo = new SomeClass();
foo.SomeMethod();
}
public void SomeMethod() {
}
}
Code blocks number 2.
public class SomeClass {
public static void main(String [] args) {
new SomeClass().SomeMethod();
}
public void SomeMethod() {
}
}
Are this two code blocks(number 1 and 2) the same? I'm confused over the different syntax during calling the method. I appreciate if someone could explain it for me.

Yes, they are functionally the same. With code block 2, however, you have no way of accessing the SomeClass object you created in the future lifespan of the program.

Yes they are same. In first case the object reference is just stored in a reference variable for future usage .
In second case the reference is not stored.

Related

Method Calls Not Working [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}
You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).
The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);

Unable to retrieve value of static variable in JAVA [duplicate]

This question already has answers here:
Why doesn't the main method run?
(3 answers)
Closed 5 years ago.
I want to access a static variable set in one Java class in another class. I am using the syntax properly I guess but I am getting null everytime.
Could someone help with this?
Class 1:
public class Test {
public static List<String> dbobj;
public static void main(String args[]) {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
Class 2 :
public class Test2 {
public void main(String args[]) {
List<String> list1= Test.dbobj;
System.out.println("List value"+list1); **//COMING AS NULL**
}
}
You have two entry points (programs) which absolutely independent of each other.
When you are calling a Test.dbobj, the main method from the Test is not executed, therefore its initialisation dbobj=accnos; is not called.
It is a bit awkward, but you could call the Test.main(args); before printing to execute that init process.
When you're within the main method of Test2, the main of Test has not been called.
The static variable dbobj has therefore its initial value, being null.
First of all you can't have 2 main functions and expect it to run both, so the better way to do this would be using a static code block in Class1 like this
static {
List<String> accnos= new ArrayList<String>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
Try this changes in your class Test2:
Test.main(args); // added
List<String> list1= Test.dbobj;
Problem is you are using static variable dbobj from class Test without initializing that given variable. As of now, dbobj is assigned value inside Test.main(), so likewise you need to invoke that method.
There is no code executed that initialized the dbobj list, when your invoke main method in Test2 class. Therefore it points to NULL.
The easiest fix is to initialize it right when it is declared :
public static List<String> dbobj list = new ArrayList<>() {
{ add("str1"); add("str2"); }
};
The other solution is to fix Test1 class as below:
public class Test {
public static List<String> dbobj;
public static void init() {
List<String> accnos = new ArrayList<>();
accnos.add("1");
accnos.add("2");
accnos.add("3");
dbobj=accnos;
System.out.println("dbobj"+dbobj);
}
}
public class Test2 {
public void main(String args[]) {
Test.init();
List<String> list1 = Test.dbobj;
System.out.println("List first value" + list1[0]); // should be OK
}
}

tricky method Overloading in java [duplicate]

This question already has an answer here:
Method overloading/overriding in Java subclass object with superclass reference variable
(1 answer)
Closed 6 years ago.
class ABC {
void doMe(String s) {
System.out.println("String");
}
}
class XYZ extends ABC {
void doMe(Object o) {
System.out.println("Object");
}
}
public class StopStart {
public static void main(String[] args){
ABC o = new XYZ();
o.doMe(null);
}
}
What will happen and why?
string class extends Object. So which doMe() will execute.
Is it a compilation error?
Overloading is resolved in compile time, according to the compile time type of the variable o. Therefore doesn't matter which methods are defined in the XYZ sub-class. Only the methods of ABC are relevant.
Therefore only void doMe(String s) is considered by the compiler, and that's the chosen method.

a function is required to be static in java [duplicate]

This question already has answers here:
cannot make a static reference to a non static method
(5 answers)
Closed 7 years ago.
The following block has an error. It requires the createArrayList function to be static. I cannot understand the reason. I appreciate if anyone can explains that to me in an understandable way.
import java.util.ArrayList;
public class Ceasefire {
public static void main(String[] args)
{
createArrayList();
System.exit(0);
}
public void createArrayList()
{
ArrayList<String> aL1 = new ArrayList<String>();
aL1.add("Item1");
aL1.add("Item2");
aL1.add("Item3");
System.out.println(aL1);
}
}
You cannot call a non-static (createArrayList) method from a static one (main). A static method can only call other static methods, but no instance methods.

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

Categories