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.
Chris

Well 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.

Similar Messages

  • Non static method cannot be referenced from a non static context

    Dear all
    I am getting the above error message in my program.
    public void testing(Vector XY){
    RecStore.checkUnits(XY);
    }method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
    I have done a wider search throughout the main class and I'm haven't got any static their either.
    Any ideas?
    Thanks
    Dan

    Yup
    I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
    But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
    RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore."

  • Accessing a variable from different context

    Hai all,
    I want to access a servlet that is defined outside of my context(application),
    I have two contexts that r running under tomcat server.
    Please help me

    Then you need to create a URLConnection to that servlet. Eg :
    URLConnection connection = new URL("http://localhost:8080/Test/TestServlet").openConnection();
    [/code[                                                                                                                                                                                                                                                                                                                                                       

  • Another question: non-static variable super cannot be referenced from ...?

    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
    thanks

    You 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.

  • Using a function from static context..

    Well I have a command line app; and it has a public static void main. Now, I made a function that writes to a file, and tried calling it from the main section, and it got mad saying I can't call it from static context. Anyway to allow it to be called from both static and non static contexts?

    otherwise create object of the class, from that object you can call a method

  • Static Context: What Does it REALLY mean?

    Friends,
    I really having this trouble of grabbing the idea of static context vs non-static context.
    Lets say I have a static method, is that mean that all items (variables and calls) inside it are assumed to be static as well?
    Thanks in advance.

    Any statement or expression inside the static method is said to "occur in a static context". In such a method - like the traditional main() method - only static members and methods can be used.
    (Statements and expressions occuring in lots of other places are also said to occur in a static context - see the JLS http://java.sun.com/docs/books/jls/third_edition/html/classes.html#296300 for details. In a loose sense what these contexts have in common is that they "belong" to the class as a whole, rather than to any specific instance: they relate to class wide things and operations.)

  • Variable from one class to another

    I have a Program that contains a JDesktop Pane, and when the program starts, it creates the "main" window as in JInternal Frame.
    When a certain check box is checked, I call an external class that creates and returns a JInternalFrame. What I need to do is have the external class get a Vector from the main class (I pass it in when i create the object), edit the Vector, then return it to the main class. If i try to create a method in the main class like "returnVector()" or whatever to get the vector back to the main class, I get the error of "Non-static variable cannot be referenced from a non-static context". How can I get around that? The NEXT issue is this: I would like to cause the JInternalFrame that is created from the external class (on the JDesktopPane in the main class) to close itself when a button in it is clicked. I'm guess I'd need a Listener somewhere. Would that listener be in the Main class or in the external one. Does this make sense? Any help would be greatly appreciated.

    Sorry, This might be a bit lengthy, but it works and illustrates my problem. I created it in NetBeans. There are the two classes I'm jusing. The issue is illustrated in the button listener on the 2nd class:
    The First:
    package javaapplication3;
    import java.beans.PropertyVetoException;
    import java.util.Vector;
    import javax.swing.JInternalFrame;
    public class NewJFrame extends javax.swing.JFrame {
        Vector <String> TestVector = new Vector <String> (0); //Vector to move around.
        public NewJFrame() {
            //add some test strings to the Vector
            TestVector.add("String1");
            TestVector.add("String2");
            TestVector.add("String3");
            initComponents();
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jDesktopPane1 = new javax.swing.JDesktopPane();
            jInternalFrame1 = new javax.swing.JInternalFrame();
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jInternalFrame1.getContentPane().setLayout(new java.awt.FlowLayout());
            jInternalFrame1.setVisible(true);
            jLabel1.setText("This is a VERY simple example");
            jInternalFrame1.getContentPane().add(jLabel1);
            jButton1.setText("Press this");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ButtonListen(evt);
            jInternalFrame1.getContentPane().add(jButton1);
            jInternalFrame1.setBounds(10, 10, 350, 120);
            jDesktopPane1.add(jInternalFrame1, javax.swing.JLayeredPane.DEFAULT_LAYER);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jDesktopPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        private void ButtonListen(java.awt.event.ActionEvent evt) {                             
            JInternalFrame newFrame;
            NewJFrame2 roadframe = new NewJFrame2(TestVector);
            newFrame= roadframe.getFrameBack();
            newFrame.setVisible(true);
            jDesktopPane1.add(newFrame);
            try {
                newFrame.setSelected(true);
            } catch (PropertyVetoException ex) {
                ex.printStackTrace();
        //created this in hopes of using it to return the vector from NewJFrame2
        public void returnVector(Vector<String> vectorAgain){
            this.TestVector=vectorAgain;
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JDesktopPane jDesktopPane1;
        private javax.swing.JInternalFrame jInternalFrame1;
        private javax.swing.JLabel jLabel1;
        // End of variables declaration                  
    }The 2nd:
    package javaapplication3;
    import java.util.Vector;
    import javax.swing.DefaultListModel;
    import javax.swing.JInternalFrame;
    public class NewJFrame2 extends javax.swing.JFrame {
        Vector <String> testVector=new Vector<String>(0);
        DefaultListModel model;
        public NewJFrame2(Vector <String> TestVector) {
            this.testVector=TestVector;
            initComponents();
        public JInternalFrame getFrameBack(){
            return jInternalFrame1;
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jInternalFrame1 = new javax.swing.JInternalFrame();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            model=new DefaultListModel();
            for (int a=0; a<testVector.size();a++){
                model.addElement(testVector.get(a));
            jList1 = jList1=new javax.swing.JList(model);
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jInternalFrame1.setVisible(true);
            jLabel1.setText("This is the 2nd class I was referencing I passed TestVector from NewFrame. It Contains:");
            jInternalFrame1.getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
            jLabel2.setText("Now I want to Edit this list here, and then send it back to NewFrame1. The button will attemp.");
            jInternalFrame1.getContentPane().add(jLabel2, java.awt.BorderLayout.SOUTH);
            jScrollPane1.setViewportView(jList1);
            jInternalFrame1.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jButton1.setText("Return Vector");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ReturnVectorButtonListener(evt);
            jInternalFrame1.getContentPane().add(jButton1, java.awt.BorderLayout.EAST);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jInternalFrame1)
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jInternalFrame1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            pack();
        }// </editor-fold>
        private void ReturnVectorButtonListener(java.awt.event.ActionEvent evt) {
        NewJFrame.returnVector(testVector);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JInternalFrame jInternalFrame1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JList jList1;
        private javax.swing.JScrollPane jScrollPane1;
        // End of variables declaration
    }

  • 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,
    Jeff

    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
    �������������� }
    ���������� }
    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 total cannot be referenced from a static context

    i am trying to write a program that uses the if-else statements and when i wrote my program i got "non-static variable total cannot be referenced from a static context" for three lines of my input.
    A:\Disks.java:20: non-static variable total cannot be referenced from a static context total = (10000 * .95 + ((diskCount - 10000) * .85));
    ^
    A:\Disks.java:22: non-static variable total cannot be referenced from a static context total = (diskCount * .95);
    ^
    A:\Disks.java:24: non-static variable total cannot be referenced from a static context System.out.print(total);
    ^
    Do you know what I did wrong?

    I apologise in advance for the general tone of this reply.....
    Ummm, let me think for a second... You referenced a non static
    variable from a static context. Yup, yup. That's it !
    If you can't figure this out, you really need to do a Java tutorial or
    buy a text book. Basically though, total is a member of some class
    and you are trying to use it from a static function. I bet you have
    something like:
    public class Test {
        public int total;
        // blah blah blah
        public static void main(String[] args) {
            // This won't work cos "total" is a member and we are static
            System.out.println(total);
            // This works cos now you have an instance to pull total
            // out of.
            Test t = new Total();
            System.out.println(t.total);
    }

  • Non-static variable aceYears cannot be referenced from a static context

    This is my error...
    investment.java:53: non-static variable aceYears cannot be referenced from a static context
    lwInvest.numberAceYears(aceYears);
    ^
    This is my code...
    public static void main (String[] args)
    investment.Invest.numberAceYears(aceYears);
    and more code
    String termInvested = JOptionPane.showInputDialog
    ("Please enter the amount of years to invest your investment.");
    int intTermInvested = Integer.parseInt(termInvested);
    and yet more code..
    public void numberAceYears (int aceYears)
    for (int aY = 5 ; aY <= aceYears; aY++)
    double aceInterest = aceCoBalance * aceCoRate /100;
    aceCoBalance = aceCoBalance + aceInterest;
    aceYears = aceYears + aY;
    Suggestions?

    Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
    For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
    http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • 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.

  • "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&ouml;k personen via personnummer och skriv personens andra uppgifter.");
    System.out.println("3. S&ouml;k personen via efternamn och skriv personens andra uppgifter.");
    System.out.println("4. S&ouml;k personen via personnummer och &auml;ndra adress.");
    System.out.println("5. S&ouml;k personen via personnummer och &auml;ndra telefonnummer.");
    System.out.println("6. S&ouml;k personen via personnummer och &auml;ndra civilst&aring;nd.");
    System.out.println("7. S&ouml;k personen vis personnummer och &auml;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&auml;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 &auml;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.

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

Maybe you are looking for