"Non-static method cannot be referenced from a static context" error - java

I have a class named Media which has a method named setLoanItem:
public void setLoanItem(String loan) {
this.onloan = loan;
}
I am trying to call this method from a class named GUI in the following way:
public void loanItem() {
Media.setLoanItem("Yes");
}
But I am getting the error
non-static method setLoanItem(java.lang.String) cannot be referenced from a static context
I am simply trying to change the variable onloan in the Media class to "Yes" from the GUI class.
I have looked at other topics with the same error message but nothing is clicking!

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)

setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.

setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}

You need to correctly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference/call them you must do so via an instance. So you either want
public void loanItem() {
this.media.setLoanItem("Yes");
}
or
public void loanItem(Media object) {
object.setLoanItem("Yes");
}
depending on how you want to pass that instance around.

Related

Java strange syntax - (Anonymous sub-class)

I have come across below strange syntax, I have never seen such snippet, it is not necessity but curious to understand it
new Object() {
void hi(String in) {
System.out.println(in);
}
}.hi("strange");
Above code gives output as strange
thanks
You've created an anonymous sub-class of Object, which introduces a method, called hi, after which you invoke this method with parameter "strange".
Let's suppose you had:
class NamedClass extends Object {
void hi(String in) { System.out.println(in); }
}
NamedClass instance = new NamedClass();
instance.hi("strange");
If this class was needed at exactly one place, there's no real need of being named and so on - by making it an anonymous class, you get rid of its name, the class gets defined and instantiated and the hi method invoked immediately within a single expression.
You've created an annonymous sub-class of Object and then invoke the method.
Four types of anonymous inner class exists :-
1)Inner class,
2)Static nested classes
3)Method local inner classes
4)Anonymous inner classes
In Annonymous inner classes,you can define,instantiate and use that inner object then and there
This is perfectly normal and is Called an anonymous class it is used very often where if u want to pass an object reference to a function you will do it with anonymous classes or for the use of callbacks, now .hi at the end is valid because you just used the new operator to instantiate an object of type Object and you have a reference to it so that's why it works.

What is the benefit to assign the parameter to another variable

I am reading a tutorial form this site.http://tutorials.jenkov.com/java-unit-testing/matchers.html
The author I believe is very experienced. I saw the code like this. I also saw someone else always like to assign the parameter of a method to a variable then use it inside the method. This one here is this line. protected Object theExpected = expected;
Can anyone please tell me, what is the benefit of this coding style? Is this trying to avoid the object status being changed or something?
What if the parameter is not an Object but a primitive variable.
And what if it is a immutable Object like String. Thank you.
public static Matcher matches(final Object expected){
return new BaseMatcher() {
protected Object theExpected = expected;
public boolean matches(Object o) {
return theExpected.equals(o);
}
public void describeTo(Description description) {
description.appendText(theExpected.toString());
}
};
}
Here is the update
I just did another test, to see if this parameter still accessible after we got the object.
package myTest;
public class ParameterAssignTest {
public static void main(String[] args) {
MyInterface myClass = GetMyClass("Here we go");
System.out.println(myClass.getValue());
System.out.println(myClass.getParameter());
}
public static MyInterface GetMyClass(final String myString){
return new MyInterface() {
protected String stringInside = myString;
#Override
public String getValue() {
return stringInside;
}
#Override
public String getParameter() {
return myString;
}
};
}
}
Output:
Here we go
Here we go
So does this mean that even we do assign this parameter to the a local variable it still works?
I do not believe assigning to theExpected achieves anything.
As expected is final it can be accessed within the anonymous class. If it were used directly in describeTo the object would not be GC'd and the reference would remain valid when the local scope in which expected was declared was left.
Possibly the author of the post you link to believes this explicit style is more readable.
It doesn't matter if theExpected is primitive or Object (though in this example it's an Object), and whether it's mutable or not.
The matches method returns an instance of an anonymous class that extends BaseMatcher (and implements the Matcher interface, assuming that's an interface).
Once it returns the instance, the local variable - expected - that was passed to it is out of scope, but the theExpected member, containing the same value as that local variable, stays within the instance, and can be used by the methods of that instance.
If you want/need to use a local variable in an inner class (in this case, an anonymous local class), the variable must be declared as final regardless if it's primitive or a reference type. This is better explained here: Why Java inner classes require "final" outer instance variables?. Quoting the best explanation IMO:
The reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
In this case, seems like the author want to keep a copy of the parameter sent to the method in the reference of the anonymous class generated for further evaluation. Once the method finishes its execution, the parameter Object expected isn't available anymore, so if you want/need to keep it then you must assign it into a field of your class.

Confusion about static methods in Java

As I understand static, it is that static methods can be called without an instance of the object needing to exist. So instead of making an object and calling the method on that object, you can just call the method on the class.
Now, I have a class Main that has the following object: public ScribbleCanvas myCanvas;. In the ScribbleCanvas class I would like to access a method of the Main-class.
Now, since there is already an instance of Main (since this called the ScribbleCanvas), how can I access a non-static method of this class? Or perhaps the better question - where is the error in my reasoning?
You could have a constructor or a setter for the ScribbleCanvas that takes a parameter as the current instance of Main.
ScribbleCanvas sc = new ScribbleCanvas(this);
or
sc.setMainClass(this);
And with those, you just reference a field to the parameter.
You can set Main instance as a member of myCanvas and use it.
The below code explains how you should do it. The testInstanceMethod is been taken as an
example for an instance method in Main class. This method should be accessible as well
public class ScribbleCanvas{
private Main mainObject = null;
public ScribbleCanvas(){
this.mainObject = new Main();
//Call instance method in mainObject (member instance)
this.mainObject.testInstanceMethod();
}
public void setMainObject(Main arg){
this.mainObject = arg;
}
public Main getMainObject(){
return this.mainObject;
}
}
For invoking static methods, you can directly put the Classname and invoke using DOT operator like Main.testStaticMethod() provided the method is accessible as well
Disclaimer : NOT tested / compiled
If I understand your question you want to:
Have an instance of the Main class, let's call it myMain.
The instance will have an instance of the ScribbleCanvas class, called myCanvas
From the ScribbleCanvas instance (myCanvas) have access to methods within myMain.
In order to do this you can:
Declare a member of type Main within ScribbleCanvas, say callingMain
Include a parameter of type Main (say paramMain) in the constructor for ScribbleCanvas
In the constructor, store paramMain in callingMain
From Main, pass in this to the constructor
Within your code, you can refer to callingMain.method()
Does this help?

Java: How To Call Non Static Method From Main Method?

I'm learning java and now i've the following problem: I have the main method declared as
public static void main(String[] args) {
..... }
Inside my main method, because it is static I can call ONLY other static method!!! Why ?
For example: I have another class
public class ReportHandler {
private Connection conn;
private PreparedStatement prep;
public void executeBatchInsert() { ....
} }
So in my main class I declare a private ReportHandler rh = new ReportHandler();
But I can't call any method if they aren't static.
Where does this go wrong?
EDIT: sorry, my question is: how to 'design' the app to allow me to call other class from my 'starting point' (the static void main).
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert, there isn't enough context.
It's really important that you understand that:
Instance methods (and fields etc) relate to a particular instance
Static methods and fields relate to the type itself, not a particular instance
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}
Java is a kind of object-oriented programming, not a procedure programming. So every thing in your code should be manipulating an object.
public static void main is only the entry of your program. It does not involve any object behind.
So what is coding with an object? It is simple, you need to create a particular object/instance, call their methods to change their states, or do other specific function within that object.
e.g. just like
private ReportHandler rh = new ReportHandler();
rh.<function declare in your Report Handler class>
So when you declare a static method, it doesn't associate with your object/instance of your object. And it is also violate with your O-O programming.
static method is usually be called when that function is not related to any object behind.
You can't call a non-static method from a static method, because the definition of "non-static" means something that is associated with an instance of the class. You don't have an instance of the class in a static context.
A static method means that you don't need to invoke the method on an instance. A non-static (instance) method requires that you invoke it on an instance. So think about it: if I have a method changeThisItemToTheColorBlue() and I try to run it from the main method, what instance would it change? It doesn't know. You can run an instance method on an instance, like someItem.changeThisItemToTheColorBlue().
More information at http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods.
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
You cannot call a non-static method from the main without instance creation, whereas you can simply call a static method.
The main logic behind this is that, whenever you execute a .class file all the static data gets stored in the RAM and however, JVM(java virtual machine) would be creating context of the mentioned class which contains all the static data of the class.
Therefore, it is easy to access the static data from the class without instance creation.The object contains the non-static data
Context is created only once, whereas object can be created any number of times.
context contains methods, variables etc. Whereas, object contains only data.
thus, the an object can access both static and non-static data from the context of the class
Since you want to call a non-static method from main, you just need to create an object of that class consisting non-static method and then you will be able to call the method using objectname.methodname();
But if you write the method as static then you won't need to create object and you will be able to call the method using methodname(); from main. And this will be more efficient as it will take less memory than the object created without static method.
Useful link to understand static keyword
https://www.codeguru.com/java/tij/tij0037.shtml#Heading79

What is "static"?

I'm beginning to program in Java.
public static void main(String[]args)
A book said that I should use static in this case, but doesn't clearly say why I should or what it means.
Could you clarify this?
The concept of static has to do with whether something is part of a class or an object (instance).
In the case of the main method which is declared as static, it says that the main method is an class method -- a method that is part of a class, not part of an object. This means that another class could call a class method of another class, by referring to the ClassName.method. For example, invoking the run method of MyClass would be accomplished by:
MyClass.main(new String[]{"parameter1", "parameter2"});
On the other hand, a method or field without the static modifier means that it is part of an object (or also called "instance") and not a part of a class. It is referred to by the name of the specific object to which the method or field belongs to, rather than the class name:
MyClass c1 = new MyClass();
c1.getInfo() // "getInfo" is an instance method of the object "c1"
As each instance could have different values, the values of a method or field with the same name in different objects don't necessarily have to be the same:
MyClass c1 = getAnotherInstance();
MyClass c2 = getAnotherInstance();
c1.value // The field "value" for "c1" contains 10.
c2.value // The field "value" for "c2" contains 12.
// Because "c1" and "c2" are different instances, and
// "value" is an instance field, they can contain different
// values.
Combining the two concepts of instance and class variables. Let's say we declare a new class which contains both instance and class variables and methods:
class AnotherClass {
private int instanceVariable;
private static int classVariable = 42;
public int getInstanceVariable() {
return instanceVariable;
}
public static int getClassVariable() {
return classVariable;
}
public AnotherClass(int i) {
instanceVariable = i;
}
}
The above class has an instance variable instanceVariable, and a class variable classVariable which is declared with a static modifier. Similarly, there is a instance and class method to retrieve the values.
The constructor for the instance takes a value to assign to the instance variable as the argument. The class variable is initialized to be 42 and never changed.
Let's actually use the above class and see what happens:
AnotherClass ac1 = new AnotherClass(10);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
Notice the different ways the class and instance methods are called. The way they refer to the class by the name AnotherClass, or the instance by the name ac1. Let's go further and see the behavioral differences of the methods:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
AnotherClass.getClassVariable(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
AnotherClass.getClassVariable(); // Returns "42"
As can be seen, an instance variable is one that is held by an object (or "instance"), therefore unique to that particular instance, which in this example is the objects referred to by ac1 and ac2.
A class variable on the other hand is only unique to that entire class. To get this point across even better, let's add a new method to the AnotherClass:
public int getClassVariableFromInstance() {
return classVariable;
}
Then, run the following:
AnotherClass ac1 = new AnotherClass(10);
AnotherClass ac2 = new AnotherClass(20);
ac1.getInstanceVariable(); // Returns "10"
ac1.getClassVariableFromInstance(); // Returns "42"
ac2.getInstanceVariable(); // Returns "20"
ac2.getClassVariableFromInstance(); // Returns "42"
Although getClassVariableFromInstance is an instance method, as can be seen by being invoked by referring to the instances ac1 and ac2, they both return the same value, 42. This is because in both instance methods, they refer to the class method classVariable which is unique to the class, not to the instance -- there is only a single copy of classVariable for the class AnotherClass.
I hope that some what clarifies what the static modifier is used for.
The Java Tutorials from Sun has a section called Understanding Instance and Class Members, which also goes into the two types of variables and methods.
Please see a nice description on Wikipedia
For example, notice how in the Math class, you can say things like
Math.Abs(x);
without having to say
Math m = new Math();
These are static methods since you don't need an instance. Instance methods are those methods that require you to have an instance of a class.
Employee e = new Employee();
e.Terminate();
A static method is one that applies to the class a whole, not any particular member. .goExtinct() would be a method of the Duck population as a whole, not any particular duck. main is public and static because is has to always be available, and its not part of any particular class.
Usually, you have to have an object, an instance of a class, in order to call methods on it, for at least two reasons:
It depends on the object which class implements the method that is being called. For example if you have an instance of a subclass, the method in the subclass will be called instead, even though the code that calls the method is the same.
Objects usually have internal state (fields), that methods can refer to. This does not work if there is no object instance.
You create object instances by calling the class' constructor:
MyObject a = new MyObject();
Static methods are methods that are not attached to object instances. They can be called by just naming the class. As a result of this they
cannot be dynamically dispatched to subclasses (which is why you get a warning when you try to call it on object instances, that is just confusing syntax)
they cannot refer to instance state (non-static fields and other non-static methods).
Many people consider static methods a bad design pattern, and advise to not use them (except for public static void main) Look up the singleton instance pattern for an alternative.
In this particular case the main method must be static, because of the way the JVM will start loading classes and creating objects. When you start a Java program the JVM will look for the definition of the class that was passed to it and load it. So java MyClass will result in loading the definition of the MyClass class.
By definition a Java program will start executing in the main() method of the class that was passed to the JVM as the class to load initially. At this point in time no instance (object) of type MyClass has been created, so the main method has to be static to allow the start of the execution of your program.
If you want to see which classes are being loaded during the execution of a Java program you can use the -verbose:class command line option.
In any object oriented programming language like Java or C++ you create classes which at the very basic level are like BluePrints of a building. You can look at a blueprint and determine how various components are connected but you cannot actually live in it. It's the same with classes and object. Classes are blueprint and you create an instance of a class which is called an Object. For the same blueprint you can have multiple buildings , same way for one class you can have multiple objects. An Object is an instance of a class. Each method in a class can be called on an Object or an instance of a class, whereas for calling static methods you actually don't need an instance, you can directly call ClassName.method() without actually creating an instance of a class.
There will be times when you will want to define a class member that will be used independently of any object of that class. Normally a class member must be accessed only in conjunction with an object of its class. However, it is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
The two types of static members are static fields and static methods:
Static field:
A field that’s declared with the static keyword, like this:
private static int ballCount:
The position of the static keyword is interchangeable with the positions of the visibility keywords (private and public, as well as protected). As a result, the following statement works, too:
static private int ballCount;
As a convention, most programmers tend to put the visibility keyword first.
The value of a static field is the same across all instances of the class. In other words, if a class has a static field named CompanyName, all objects created from the class will have the same value for CompanyName.
Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first.
Static method:
A method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications run in a static context by default.
One of the basic rules of working with static methods is that you can’t access a nonstatic method or field from a static method because the static method doesn’t have an instance of the class to use to reference instance methods or fields.

Categories