Static/non-static
Hi!
I've read some docs, but can't seem to find an adequate answer to this:
Why can't a non-static field or method be referenced by a static method and vice versa?
What's the problem exactly?
Thanks in advance!
Wow, I've seemed to have touched on something here. I guess I should clarify what I mean.
deenen is correct in what I was talking about. In that when you have a static instance variable the memory space is shared by all instances of the class.
Now if it is good practice or style to do such a thing that is another matter. The talk about how you can't change a static variable is incorrect. The static keyword only means that there is no need for an explicit parameter (or implicit, I always mess the two up). Because it implies the keyword "this".
The keyword final is used to make it so that you can not change a variable once it has been initialized.
I have used this static instance variable to my advantage only in debugging objects. When I have lots of objects and they have to all keep the same state I sometimes put a static variable in the class and keep testing it to make sure that the state never changes. Probably bad practice, but like I said, only for debugging. That way I can tell usually when the state changed (which is good in threaded apps). But not which object it was changed on.
Similar Messages
-
Error on compile - non-static variable can not be referencedfrom static con
Error on compile happening with addButton?
Thanks
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
public class Log implements ActionListener {
JButton addButton;
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridy = 3;
c.gridx = 0;
JLabel callsignLabel= new JLabel("Callsign");
pane.add(callsignLabel, c);
c.gridy = 3;
c.gridx = 1;
JLabel nameLabel= new JLabel("Name");
pane.add(nameLabel, c);
c.gridy = 3;
c.gridx = 2;
JLabel timeLabel= new JLabel("Time");
pane.add(timeLabel, c);
c.gridy = 3;
c.gridx = 3;
JLabel dateLabel= new JLabel("Date");
pane.add(dateLabel, c);
c.gridy = 3;
c.gridx = 4;
JLabel frequencyLabel= new JLabel("Freq ");
pane.add(frequencyLabel, c);
c.gridy = 3;
c.gridx = 5;
JLabel locationLabel = new JLabel("Country/State");
pane.add(locationLabel, c);
c.gridy = 5;
c.gridx = 0;
addButton = new JButton("Add");
pane.add(addButton, c);
addButton.addActionListener(this);Thank you for the reply
I am new to Java
What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again. -
Using a non-static vector in a generic class with static methods
I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
package genericset;
import java.util.*;
public class GenericSet<E>{
private Vector v;
public GenericSet(Vector vec) {
v = vec;
private <T extends Comparable> Item<T> get(int index) {
return (Item<T>) v.get(index);
public static <T extends Comparable> GenericSet<T> initialize() {
return new GenericSet<T>(new Vector());
public Vector getVector() {
return v;
public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
GenericSet<T> g = assign(z);
Vector v = g.getVector();
if (!member(g,i))
v.addElement(i);
return g;
public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
GenericSet<T> g = assign(z);
Vector v = g.getVector();
if (member(g,i))
v.remove(i);
return g;
public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
Vector v = z.getVector();
return v.contains(i);
public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
Vector v1 = z1.getVector();
Vector v2 = z2.getVector();
if((v1 == null) && (v2 != null))
return false;
return v1.equals(v2);
public static <T extends Comparable> boolean empty(GenericSet<T> z) {
return (cardinality(z) == 0);
public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = assign(z1);
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
if(member(z1, elem))
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z1); i++) {
Item<T> elem = z1.get(i);
if(!member(z2, elem))
insert(g, elem);
for(int i=0; i<cardinality(z2); i++) {
Item<T> elem = z2.get(i);
if(!member(z1, elem))
insert(g, elem);
return g;
public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
GenericSet<T> g = initialize();
for(int i=0; i<cardinality(z); i++) {
Item<T> elem = z.get(i);
insert(g, elem);
return g;
public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
for(int i=0; i<cardinality(z1); i++) {
Item<T> elem = z1.get(i);
if(!member(z2, elem))
return false;
return true;
public static <T extends Comparable> int cardinality(GenericSet<T> z){
Vector v = z.getVector();
return v.size();
}The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this: public static EditorBean findEditorData( String username, EditorBean editorData )
return editorData.ed.findEditor( username );
} -
How can I use non-static func in a static func?
Hello guys,
I have a func processFiles which is static, i wanna use a func from another class FileData in processFile func and i dnt wanna make processFile non-static, what should i do?
my code:
public class Library {
private FileData file = new FileData();
public static void main(String[] args){
try{
Library lib = new Library();
lib.processFiles(args);
catch(IOException e)
System.err.println("IOException occurred in main.");
System.exit(0);
@SuppressWarnings("unchecked")
public static void processFiles(String[] fileNames) throws IOException {
file.getMaterial();// I get error here;
class FileData{
getMaterila() {}
}1) it's not "func", it's "method".
2) Create a FileData instance and call the method on that
3) Read the basic tutorials about what "static" means, and put the error message into Google. -
Calling a non-static method from another Class
Hello forum experts:
Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
populates a JTable.
2. User selects a row in the table and then clicks a button on the icon toolbar
which is part of UIMenu class.
3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
(a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
== OR ==
(b). I could declare UpdateDatabase() as static and call this method without
creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
object specific data.
With option (b), if I declare the method as static, the variables used in the method would also have to be static.
The variables, in which case, would not be object specific.
Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
way?
Any ideas or thoughts will be of tremendous help. Thanks in advance.Hello Forum:
Danny_From_Tower, Encephalatic: Thank you both for your responses.
Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
and declared as public.
public class MyMenu {
public JButton btnAccept;
//Constructor
public MyMenu() {
btnAccept = new JButton("Accept");
} I instantiate an object for MyMenu class in the main application class MyApp.
public class MyApp {
private MyMenu menu;
//Constructor
public MyApp(){
menu = new MyMenu();
public void openOrder(){
MyGUI MyIntFrame = new MyGUI(menu.btnAccept);
}I pass this button all the way down to the class detail02. Now I want to set up a listener for this
button in the class detail02. I am not able to do this.
public class MyGUI {
private JButton acceptButton;
private detail02 dtl1 = new detail02(acceptButton);
//Constructor
public AppGUI(JButton iButton){
acceptButton = iButton;
public class detail02{
private JButton acceptButton;
//Constructor
public detail02(JButton iButton){
acceptButton = iButton;
acceptButton.addActionListener(new acceptListener());
//method
private void acceptListener_actionPerformed(ActionEvent e){
System.out.println("Menu item [" + e.getActionCommand( ) + "] was pressed.");
class acceptListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
acceptListener_actionPerformed(e);
} I am not able to get the button Listener to work. I get NullPointerException at this line
acceptButton.addActionListener(new acceptListener());in the class detail02.
Is this the right way? Or is there a better way of accomplishing my objective?
Please help. Your inputs are precious! Thank you very much for your time! -
Non-static variable Help needed
Hi, I am creating a multi threaded web server but get the following error
non-static variable this cannot be referenced from a static context
HttpRequest request = new HttpRequest(connectionSocket);
Please could someone help.
Many Thanks
import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public static void main(String argv[]) throws Exception
// Set the port number.
int port = 6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while (true) {
// Listen for a TCP connection request.
Socket connectionSocket = listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request = new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close();import java.io.* ;
import java.net.* ;
import java.util.* ;
public final class MultiWebServer
public MultiWebServer(){
try{
// Set the port number.
int port=6789;
// Establish the listen socket.
String fileName;
ServerSocket listenSocket=new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
while(true){
// Listen for a TCP connection request.
Socket connectionSocket=listenSocket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request=new HttpRequest(connectionSocket);
// Create a new thread to process the request.
Thread thread=new Thread(request);
// Start the thread.
thread.start();
}catch(IOException ioe){
}catch(Exception e){
public static void main(String argv[]) throws Exception
new MultiWebServer();
final class HttpRequest implements Runnable
final static String CRLF = "\r\n";
Socket socket;
String requestMessageLine;
String fileName;
Date todaysDate;
// Constructor
public HttpRequest(Socket socket) throws Exception
this.socket = socket;
socket = null;
// Implement the run() method of the Runnable interface.
public void run()
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
private void processRequest() throws Exception
// Get a reference to the socket's input and output streams.
//InputStream is = new InputStream(socket.getInputStream());
//DataOutputStream os = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(
socket.getOutputStream());
// Set up input stream filters.
requestMessageLine = inFromClient.readLine();
//BufferedReader br = null;
// Get the request line of the HTTP request message.
String requestLine = null;
// Display the request line.
System.out.println();
System.out.println(requestLine);
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET"))
fileName = tokenizedLine.nextToken();
if ( fileName.startsWith("/")==true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int)file.length();
FileInputStream inFile = new FileInputStream(fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
/* Send the HTTP header */
outToClient.writeBytes("HTTP/1.1 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".jpeg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
if (fileName.endsWith(".html"))
outToClient.writeBytes("Content-Type: text/html\r\n");
if (fileName.endsWith(".htm"))
outToClient.writeBytes("Content-Type: text/html\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
/* Now send the actual data */
outToClient.write(fileInBytes, 0, numOfBytes);
socket.close();
else
System.out.println("Bad Request Message");
todaysDate = new Date();
try {
FileInputStream inlog = new FileInputStream("log.txt");
System.out.println(requestMessageLine + " " + todaysDate );
FileOutputStream log = new FileOutputStream("log.txt", true);
PrintStream myOutput = new PrintStream(log);
myOutput.println("FILE -> " + requestMessageLine + " DATE/TIME -> " + todaysDate);
catch (IOException e) {
System.out.println("Error -> " + e);
System.exit(1);
socket.close(); -
Non-static variable being used in static context
I am currently attempting to write a basic user login system using basic applets. I have two JTextFields named "userText" and "passText".
What i am attempting to do is use the ".getText()" method to get the text out of the JTextField and verifying the string against a string already in a file using the bufferedReader, etc.
However when i try to compare the string in the file with the one in the text field using the following code:
if ((line.compareTo(username)) == 0)
i get the following error...
"non-static variable being used in a static context"
Any ideas?The static method doesn't know about instances of the class instead you pass the instance to the method:
static public void myMethod(MyClass instance, String var) {
if(instance.line.compareTo(var))
And then the call would be:
MyClass.myMethod(anInstance, userName); -
Problem with OSB 11g - Unable to call non-static java methods
I have a problem in OSB. Unable to see any java methods when loading java callout. I have checked the java classes in the .jar file and they are all non-static java methods.
Is there any way where OSB is able to see this non-static java methods?
Need help urgently!
Thanks!Technical standpoint: Do you know why OSB is not able to call non-static methods?
This is by design. Ability to call non-static methods require Object creation which adds additional complexity. eg How to pass variables in constructor?. How/where to store created object for use across across pipeline instance?. Object life cycle (when and how to create object) etc. To avoid above complexites static methods are only supported.
"a lot of non-static method to call" just for my understanding what are the number involved?. If number is too high you can always request for a enhancement.
Thanks
Manoj -
Abstract method versus static and non-static methods
For my own curiosity, what is an abstract method as opposed to static or non-static method?
Thanks>
Following this logic, is this why the "public static
void main" 0r "Main" method always has to be used
before can application can be run: because it belongs
to the class (class file)?
Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
RObin -
Non-static variable cant accessed from the static context..your suggestion
Once again stuck in my own thinking, As per my knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static context....'
Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void main(String ar[]){ ////static context
������������ int counter=0; ///Non static variable
������������ for(;counter<10;) {
�������������� counter++;
�������������� System.out.println("Value of counter = " + counter) ; ///working fine
�������������� }
���������� }
Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffOnce again stuck in my own thinking, As per my
knowledge there is a general error in java.
i.e. 'Non-static variable cant accessed from static
context....'
Now the thing is that, When we are declaring any
variables(non-static) and trying to access it within
the same method, Its working perfectly fine.
i.e.
public class trial{
���������� public static void
main(String ar[]){ ////static context
������������ int counter=0; ///Non
static variable
������������ for(;counter<10;) {
�������������� counter++;
��������������
System.out.println("Value
of counter = " + counter) ; ///working fine
�������������� }
���������� }
w the question is that if we are trying to declare a
variable out-side the method (Non-static) , Then we
defenately face the error' Non-static varialble can't
accessed from the static context', BUT here within
the static context we declared the non-static
variable and accessed it perfectly.
Please give your valuable suggestions.
Thanks,
JeffHi,
You are declaring a variable inside a static method,
that means you are opening a static scope... i.e. static block internally...
whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
But if you put ... it will be considered as redundant by compiler.
More over, static context does not get "this" pointer...
that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller. -
Non-static variable from a static context
This is the error i get . If i understand the error correctly it says im using a static variable when i shouldnt be? Or is it the other way round? below the error is the actual code....
The error...
Googler.java:27: non-static variable this cannot be referenced from a static context
submitButton.addActionListener(new ButtonHandler());The code...
JButton submitButton = new JButton("Submit Query");
submitButton.addActionListener(new ButtonHandler());thanks for the response.
I have already tried what you said but I tried it again anyway and i get the same error more less...
Googler.java:28: non-static variable this cannot be referenced from a static context
ButtonHandler buttonHandler = new ButtonHandler();here is part of my code
public class Googler
static JTextField input1, input2;
public static void main(String[] args)
JFrame myFrame = new JFrame("Googler v1.0");
Container c = myFrame.getContentPane();
JLabel lab1 = new JLabel("Enter Google Query:");
JLabel lab2 = new JLabel("Enter Unique API Key:");
input1 = new JTextField(15);
input2 = new JTextField(15);
JRadioButton radSearch = new JRadioButton("Search Query");
JRadioButton radCached = new JRadioButton("Cached Query");
JButton submitButton = new JButton("Submit Query");
ButtonHandler buttonHandler = new ButtonHandler();
submitButton.addActionListener(buttonHandler);
ButtonGroup group = new ButtonGroup();
group.add(radSearch);
group.add(radCached);Ive tried declaring buttonHandler as a static variable and this dosn't work either. I've never had this problem before it must be something silly im missing...?
Thanks
Lee -
Non-static variable from static context?
Hi,
I've created a program using swing components
and I've set up a addActionListener to a button,
button.addActionListener(this);
when try and compile I get the following error:
non-static variable this cannot be referenced from a
static context
button.addActionListener(this);
I've checked site and my notes I don't seem to have
done anything different from programs that have compiled
in the past.
I'm currently doing a programming course so I'm fairly
new to Java, try not to get to advanced on me :)
Thx in advance for any help.
ChrisWell what is declared static? If I remeber right this error means that you have a static method that is trying to access data it does not have access to. Static methods cannot access data that is intance data because they do not exist in the instance (not 100% sure about this but I believe it is true, at the very least I know they do not have access to any non-static data). Post some more of your code like where you declare this (like class def) and where you set up the button.
-
Non static variable in static context
import java.util.Scanner;
public class project4_5 {
int die1, die2;
int comptotal = 0, playertotal = 0, turntotal = 0;
int turn, comprun = 0;
String playername;
String action = ("R");
Scanner scan = new Scanner(System.in);
public static void main (String[] args)
PairOfDice mydie = new PairOfDice();
System.out.println("!!!!!!PIG!!!!!!");
System.out.println();
System.out.println("Enter your name! ");
playername = scan.nextLine();
while(playertotal>100 && comptotal>100){
while(action.equalsIgnoreCase("R")){
System.out.println(playername+" roll or pass the die (R/P) ");
action = scan.nextLine();
if(action.equalsIgnoreCase("P"))
break;
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("You rolled a "+die1+" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("You rolled a 1, you lose your points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("You rolled snake eyes, all points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
System.out.println("Would you like to roll or pass? (R/P)");
if(action.equalsIgnoreCase("P")){
playertotal = playertotal+turntotal;
turntotal = 0;
while(turntotal<=20||turns!=run){
turn = (int) (Math.random() * 5 + 1);
mydie.roll();
die1 = mydie.getFace1();
die2 = mydie.getFace2();
System.out.println("Computer rolled a "+die1+
" and a "+ die2);
if(die1==1||die2==1){
turntotal = 0;
System.out.println("Computer rolled a 1 he loses hi points"
+" for this turn.");
break;
else if(die1==1&&die2=1){
playertotal = 0;
System.out.println("Computer rolled snake eyes, his points have"
+ " been lost.");
break;
else
turntotal= turntotal+die1+die2;
comprun++;
turntotal = 0;
}here is code for a dice game i made...and when i compile it practically every variable gets an error saying non-static variable can not be referenced from a static context....anyone kno what this means or how i go about fixing it...i think it has something to do with assigning the return variable from my getFace method to die1 and die 2...idk how to fix it tho
if u need it my die class is below
public class PairOfDice
int faceValue1, faceValue2;
public PairOfDice()
faceValue1 = 1;
faceValue2 = 1;
public void roll()
faceValue1 = (int) (Math.random() * 6 + 1);
faceValue2 = (int) (Math.random() * 6 + 1);
public int getFace1 ()
return faceValue1;
public int getFace2 ()
return faceValue2;
It means what it says -- that you're trying to use a non-static thing (like a method or a field) from a static thing (like your main method).
You can either make everything static (which isn't great -- it flies in the face of object-oriented programming) or instantiate an object.
If you want to do the latter, then try this: make your main method instantiate a method, and run it, like this:
public static void main(String[] argv) {
project4_5 game = new project4_5();
game.play();
}Then create a method called play:
public void play() {
// put everything that's currently in main() in here
}See if that fixes it for you. -
Help me please~ non-static variable rs cannot be referenced ...
i make counter
but this error occurrence
only i doing resultset make and closed
why non-static variable rs ....
i am sorry i don't speak English ...
help me please..
error message
non-static variable rs cannot be referenced from a static context
source
===============================================
package jjaekim;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count{
Statement stmt;
ResultSet rs;
ResultSet rs2;
Connection conn;
//DBPoolManager dbpm;
public static String add(HttpServletRequest request){
try{
int year =0;
int month=0;
int date =0;
int hour =0;
int min =0;
int week =0;
String str_date=new String();
String str_time=new String();
String referer_url =request.getHeader("Referer");
String infomation =request.getHeader("User-Agent");
String ip =request.getRemoteAddr();
int access_date=0;
int access_time=0;
Calendar cal =Calendar.getInstance();
year =cal.get(cal.YEAR);
month =cal.get(cal.MONTH) + 1;
date =cal.get(cal.DATE);
hour =cal.get(cal.HOUR_OF_DAY);
min =cal.get(cal.MINUTE);
week =cal.get(cal.DAY_OF_WEEK);
access_date =(month*100)+date;
access_time =(hour*100)+min;
if(access_date<1000)
str_date="0"+new Integer(access_date).toString();
else
str_date=new Integer(access_date).toString();
if(access_time<100)
str_time="0"+new Integer(access_time).toString();
else
str_time="0"+new Integer(access_time).toString();
}catch(Exception e){
//System.out.print("Exc"+e.getMessage());
//return false;
finally{
if(rs!=null){
try{ rs.close();}catch(Exception e){}
if(rs2!=null){
try{ rs2.close();}catch(Exception e){}
if (stmt!=null){
try{ stmt.close();}catch(Exception e){}
//if (conn!=null){
try{ conn.close(); }catch(Exception e){}
//return back;
/* public static void main(String[] args)
System.out.println("Hello World!");Hello jjaekim,
if rs is a class variable (the same value for all objects),
try this (more likely to be the right solution) :
static ResultSet rs;
instead of :
ResultSet rs;
if rs has a different values in different objects,
then you should add the object name when using it like this :
myObject.rs or this.rs -
class a
int i;
int j=2;
a(int i)
this.i=i;
public class b extends a
b()
super(8);
public static void main(String args[])
b test=new b();
System.out.print(test.i);
test.j=1;
System.out.print("test.j="+test.j);
System.out.print("super.j="+super.j);
b.java:28: non-static variable super cannot be referenced from a static context
System.out.print("super.j="+super.j);
^
1 error
thanksYou cannot call "super" from a static context. Just like you can't use "this" or call any non-static methods in a static context.
Try with test.super.j, although I'm not sure if it works. But you can call super.j in a non-static context, e.g. in your constructor, or in a non-static method. -
"non-static variable cannot be referenced from a static contex"
Hi, i'm writing a booking program at school and i'm getting 27 "non-static variable cannot be referenced from a static contex" errors. I can't find anything wrong with the code so I'm just asking you guys to look it through..
public class bokningsmeny
Bokning[] bokningslista = new Bokning[1000];
String fornamn;
String efternamn;
String civilstand;
String adress;
String personnr;
String telefonnr;
int regnr;
double inkomst;
public static void main(String[] args)
for(;;)
System.out.println("\nMeny");
System.out.println("________\n");
System.out.println("1. Mata in nya personer.");
System.out.println("2. Sök personen via personnummer och skriv personens andra uppgifter.");
System.out.println("3. Sök personen via efternamn och skriv personens andra uppgifter.");
System.out.println("4. Sök personen via personnummer och ändra adress.");
System.out.println("5. Sök personen via personnummer och ändra telefonnummer.");
System.out.println("6. Sök personen via personnummer och ändra civilstånd.");
System.out.println("7. Sök personen vis personnummer och ändra inkomst");
System.out.println("8. Skriv ut alla personer med givet namn.");
System.out.println("9. Skriv ut alla personer med givet efternamn");
System.out.println("10. Skriv ut alla personer med given adress");
System.out.println("11. Skriv ut hela listan");
System.out.println("12. Avsluta\n");
int menyval = Keyboard.readInt();
System.out.println("\n");
switch(menyval)
case 1:
System.out.println("Mata in nya personer.\n______________________\n");
boolean BOOuppgifter = false;
for(int i = 0; i <= 1000; i++)
if(bokningslista +== null)+
+{+
+SkrivInUppgifter();+
+System.out.println("\nStämmer informationen? (Y/N)");+
+boolean BOOcase1yesorno = IsInputCorrect();+
+if(BOOcase1yesorno == true)+
+{+
+System.out.println("\nBokningen lyckades!\n");+
+bokningslista += new Bokning(fornamn, efternamn, civilstand, adress, personnr, telefonnr, regnr, inkomst);
++++else if(BOOcase1yesorno == false
++++System.out.println("\nBokningen avbruten.\n")
++++break
++++++break
++++case 2
++++System.out.println("Sok person med personnummer och ändra uppgifter.")
++System.out.println("___________________________________________________________\n")
++System.out.print("Skriv in sokord: ")
++String query = Keyboard.readString()
++query = query.toUpperCase()
++String personnummersok
++boolean contains
++int antal = 0
++boolean BOOcase2result = false
++System.out.println("Resultat: \n_________\n")
++for(int i = 0; i < 1000; i++
++++if(bokningslista +!<b<br />+<em<b<br />+++personnummersok = (bokningslista+.hamtaPersonnum()).t
++++contains = personnummersok.con
++++if(cont
+<<br />++++BOOcase2r
++++ant
++++fornamn = bokningslist
+++++efternamn = boknin
++++++personnr
+++++++System.out.println(antal + ". " + fornam
++++<e<br />+++++++System.out.pri<br<br />+++++<em<br />+++++++System.out.println("\nVilket sokresultat vill du v&bdquo
++++<<br />+++++++if(case2ch
+++++++System.ou
+++<e<<br />+++<em<br />++++
++<em<br />+++++++System.out.p
+++++<e<br />+++<<br<br /<br />+++++++System.out.printl
+++<em<br />+++++<em<br />++
<e<br />++++++++Sy
+++++
++++++<e<br /><em<br />++++++++<<br />+++++<e<br />+++
+++<<br />+++++++++else if(case11exit != 'y' &<br<br />+<<br />++++
++++
+++++
++++<e<br />+++++++
++++<em<br />+++++
+++<em<br />+++++<em<br />++++<<br />++++++
++++<e<br />+++++++<e<br />++<em<br />++++<e<br />+++<<br />+++++++++System.out.println("\n\nNamn: " + fornamn + "
++++++++++ "\nHemadress: " + adr
++++++++++ telefon
+<<br />+++++++++Syste
++++<em<br />+++++++++if(correct
<em<br />++<em<br />++<<br />++++<e<br /><<<br /><e<br />+++++++++I have another file with the Bokning.java class in it but I know for sure that its error free. Notice that I'm not nearly done with the program, theres like 10 more 'cases' to be created but I dont w
++<em</p>Your code goes "+" crazy there, but here is your problem:
public class B extends A {
public void method() {}
public static void main(String[] args) {
//method(); //non-static method method() cannot be referenced from a static context
B b = new B();
b.method();
}You need to be clear about the difference between static methods and non-static (instance) methods. Instance methods are applied to objects.
Maybe you are looking for
-
500 Internal Server Error while using BEx Web Application
Hello All, Kindly help me in resolving below issue which is getting popped up for only few people, when they are clicking some of the MSS links. 500 Internal Server Error Failed to process request;contact your system administrator Error Summary Excep
-
Passing values to APEX_UTIL.JSON_FROM_SQL
What I'm trying to do in my OnDemand application process is something like: declare lv_ename varchar2(10) := 'BLAKE'; begin APEX_UTIL.JSON_FROM_SQL('select empno,ename,job from emp where ename = '||lv_ename||'') end; What I get is: ORA-20001: get_dbm
-
Terminate air application from browser . Help !
I have managed to call AIR application from flex application using airSWF.launchApplication(appID, pubID, arguments); How can i stop the AIR application from the flex application running in browser. Any help would be helpful.
-
Starting this morning Adobe reader has quit working. I have version 10.0.1 on an HP running Windows XP with service pack 3 . When Adobe loads I get an error message " Adobe has encountered a problem and must shut down.......' When I go to the Adobe
-
Error when run the eclipse first time
show this message: 未正确配置 ABAP 通信层. 这可能是缺少 Microsoft Runtime DLLs VS2010 所造成的. 请查询安装指南或下载页面以了解有关如何安装此组件的更多详细信息. Native library sapjco3 is too old. Found library C:\Windows\System32\sapjco3.dll has version "720.612", but required is at least version "7