This question already has an answer here:
An object reference is required for the non-static field, method, or property
(1 answer)
Closed 9 years ago.
Here is the my class..
public class Oop {
int count = 0;
public static void main(String args[])
{
this.count(15, 30);
System.out.print(this.count);
}
public void count(int start, int end)
{
for(;start<end; start++)
{
this.count = this.count + start;
}
}
}
I can't call count function inside of main function. Reason is static and non-static functions. I'm really new for Java. How can i use count inside of main? What i need to learn?
You need to instantiate Oop and then call the method with it, like this:
Oop oop = new Oop();
oop.count(1,1);
For further information check this out: Difference between Static methods and Instance methods
You should make the count function and the count variable static too.
That's the least of your worries - once you've called the method, you won't be able to access the result.
You must create an instance of your class, and use that instance to call your method and get the result:
public static void main(String args[]) {
Oop oop = new Oop();
oop.count(15, 30);
System.out.print(oop.count);
}
Related
This question already has answers here:
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 3 years ago.
How do I call a function of the same class in java without using an object?
I tried this but got an error:
'non-static method facti(int) cannot be referenced from a static context'
System.out.print(facti(number));
public class Facto {
int i, fact =1;
int facti(int num){
if(num == 0){
System.out.print("For Zero ");
return 1;
}
else
for (i = 1; i <= num; ++i)
{
fact = fact * i;
}
return fact;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number for factorial : ");
int number = sc.nextInt();
Facto f1 = new Facto();
System.out.println(f1.facti(number));
}
}
Simple answer: you can't.
Your main method is 'static' it only can call other static methods (in the same class) or methods of an object. So you either can make "facti" static, too. Or you create an object: Facto f = new Facto(); f.facti(13); and call facti on that object.
Methods in Java are bound to objects unless specified otherwise. For example, consider the function foo(String str) in the class Bar:
public class Bar {
public void foo(String str) {
doSomething(this);
System.out.println(str);
}
}
This method is "attached" to a particular instance of the class Bar, meaning that it is effectively passed in as another parameter (e.g. like foo(String str, Bar this)). In Java, this is a reserved keyword, and refers tho this "hidden parameter".
Since this method has this hidden parameter, you must call it on an instance of Bar, for example:
Bar bar = new Bar();
bar.foo("hello");
If you just call: Bar.foo(), the "hidden parameter" does not know what it should be, and so this fails at compile time.
If, however, you do not need to refer to a particular instance during your method, you can mark it as static. This means you can call it on a class, rather than a type, like Bar.foo();
The error you are receiveing (non static method cannot be refernenced from a static context) is saying:
you are trying to call a non-static method facti(int i) (or, with a "hidden parameter", facti(int i, Facto facto)).
The context (i.e. the method you called it from: public static void main(String[] args)) is a static method, and so does not have this hidden parameter.
To fix it, either:
Make your method static, to avoid the need for a particular instance of Facto
Create an instance using new Facto(), and call it on that: e.g. new Facto().facti(123);
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
I'm a beginner and I'm starting to learn programming by doing some
exercises...
Why this simple java code gives me an error?
class HelloWorldEdited {
public int a = 5;
public int b = 2;
public static int sum() {
return a + b;
}
public static void main(String[] args) {
HelloWorldEdited obj = new HelloWorldEdited();
System.out.println(obj.sum());
}
}
I think it's because you are accessing "non static" properties (a, b) from a static method (sum), this operation is forbidden.
Try to change
public static int sum()
to
public int sum()
To understand the "static" modifier I suggest you to read:
official tutorial
The method sum() is static. In this method you can't access variables "non static".
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Closed 7 years ago.
I started creating a Hangman game. I want to have a main class, and a method class. I want to get a secret word, but I get an error:
non-static method getWord() cannot be referenced from a static context.
Maybe I get this error because no object has been created? What's wrong here and how do I fix this?
PS: maybe implementing it with enum could be better, but I want to start this way.
public class HangmanMain {
public static void main(String[] args) {
String secretWord; /* chosen secret word*/
secretWord = HangmanUtil.getWord();
System.out.println("");
}
}
public class HangmanUtil {
private String[] wordBank = {"pool","ice", "america", "hook", "book", "glass" , "hint", "giraffe"," elephant", "ocean","market"};
String guess;
private int bodyPartsLeft;
String getWord(){
int len = wordBank.length;
int rand = (int)(Math.random() * (len + 1));
return wordBank[rand];
}
}
You answered yourself :
Maybe I get this error because no object has been created ?
Either create a new instance of HangmanUtil or make the HangmanUtil.getWord() method static.
EDIT : considering it's a utility class, I believe second option is better : make HangmanUtil a static class with static methods.
You can't call a method via ClassName.methodName() unless the method is static.
If you want to call a non-static method, you need an instance. E.g.
HangmanUtil hu = new HangmanUtil();
secretWord = hu.getWord();
If you don't want to make an instance, then your method needs to be be marked static, and any other methods or fields it references must also be static.
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
Hi I have this piece of code and i am really confused to why i have to make the lel method static.The error is this "non static method cant be referred from static content". Usually when I create methods either to construct new objects or to manipulate objects in the main method I do not get this error message.Plus, i never declared e to be static!!. can someone please explain to me why this occurring?? Thank you :)
class x {
public static void main(String[]args){
int e= 2232;
e= lel(e);
}
int lel(int k){
return k+1;
}
}
There are two solutions you could implement. The first option is to make your int lel(int k) a static method which would look like static int lel(int k)
Your other option is to declare a new object of your class x and use that for your lel method within main as MickMnemonic suggested in the comments. That code would look like:
e = new x().lel(e);
I believe the simplest thing would be to make the lel method static but it is up to you.
A deeper explanation of static methods can be found here.