Does class/static context make an object?

Howdy all!
I know that for every class there exists a 'static context' in which all static members of a class operate - methods, variables or classes.
I also know that there is a method getClass() which retrieves a Class object.
My question is: does this mean that Java considers the class or static context of a class to be an object in its own right?
Having static members of a class implies that you have a static state - and an obvious choice is to have an object to store that state.
Is this correct? Is there something I have missed?
Rob

Hi,
Being no expert, I would say that you are on the right track. Each class loaded by a java.lang.ClassLoader is represented in Java by an object of class java.lang.Class.
The static memebers of a class are local to this instance of the class. This can be easily verified by loading the same class two times (can be done, for example, by writing your own ClassLoader). Then when you set a static member in an object of the first class, you will not see the change in objects instantiated from the later class, although it is of the same type.

Similar Messages

  • Question about static context when using classes

    hey there.
    i'm pretty new to java an here's my problem:
    public class kreise {
         public static void main (String[] args) {
             //creating the circles
             create a = new create(1,4,3);
             create b = new create(7,2,5);
             System.out.println(a);
             System.out.println(b);
             //diameters...unimportant right now
             getDiameter a_ = new getDiameter(a.radius);
             getDiameter b_ = new getDiameter(b.radius);
             System.out.println(a_);
             System.out.println(b_);
             //moving the circles
             double x = 2;
             double y = 9;
             double z = 3;
             a = create.move();
             System.out.println(a);
    }creating a circle makes use of the class create which looks like this:
    public class create {
        public double k1;
        public double k2;
        public double radius;
        public create(double x,double y,double r) {
            k1 = x;
            k2 = y;
            radius = r;
        public create move() {
            k1 = 1;
            k2 = 1;
            radius = 3;
            return new create (k1,k2,radius);
        public String toString() {
        return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
    }now that's all totally fine, but when i try to usw create.move to change the circles coordinates the compiler says that the non-static method move() can't be referenced from a static context. so far i've seen that my main() funktion MUST be static. when declaring the doubles k1, k2, and radius in create() static it works, but then of course when having created the second circle it overwrites the first one.
    i pretty much have the feeling this is very much a standard beginner problem, but searching for the topic never really brought up my problem exactly. thanks in advance!

    You can't access a non-static method from within a static context. So, you have to call move() from outside of the main method. main has to be static because, in short, at least one method has to be static because there haven't been any objects initialized when the program is started. There are more fundamental problems than with just the static context issue.
    I'm confused by your code though. You call create.move(), but this would only be possible if move() was static, and from what I see, it's not. Now that's just one part of it. My second issue is that the logic behind the move() method is very messy. You shouldn't return a newly instantiated object, instead it should just change the fields of the current object. Also as a general rule, instance fields should be private; you have them as public, and this would be problematic because anything can access it.
    Have you heard of getters and setters? That would be what I recommend.
    Now, also, when you are "moving" it, you are basically creating a new circle with completely differently properties; in light of this, I've renamed it change(). Here would be my version of your code:
    public class CircleTester {
        public static void main (String[] args)
             //Bad way to do it, but here's one way around it:
             new CircleTester().moveCircle();
        private void moveCircle()     //really a bad method, but for now, it'll do
            Circle a = new Circle(1,4,3);
            Circle b = new Circle(7,2,5);
            System.out.println(a);
            System.out.println(b);
            //diameters. Don't need to have a new getDiameter class
            double a_ = a.getRadius() * 2;     //Instead of doing * 2 each time, you could have a method that just returns the radius * 2
            double b_ = b.getRadius() * 2;
            System.out.println(a_);
            System.out.println(b_);
            //move the circle
            a.change(2,9,3);
            System.out.println(a);
    public class Circle {
        private double k1;
        private double k2;
        private double radius;
        public Circle(double x,double y,double r)
            k1 = x;
            k2 = y;
            radius = r;
        public void change(int x, int y, int r)
            k1 = x;
            k2 = y;
            radius = r;
        public String toString()
             return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
        public double getRadius()
             return radius;
    }On another note, there is already a ellipse class: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/geom/Ellipse2D.html

  • New operator in static context - how to make it work

    pdftest.java:57: non-static variable this cannot be referenced from a static context
    PageNumberer pn = new PageNumberer();
    Is it basically that I can't use the new operator in my main function because main functions have to be static in java? What's the deal here?
    I had this app working as a Java SERVLET, so all i had to do to port it over was replace the doGet method with main and remove all references to servlet specific stuff, etc. Had to make all my methods static too so main could call them, but that's all fixed. And now the thing that makes it not compile is the new operator!?!?
    public class pdftest
         ....//private static members
              /* subClass to handle page numbering of pdf */
              class PageNumberer extends PdfPageEventHelper
         public static void main(String[] args)
              PageNumberer pn = new PageNumberer();
         ....//other methods, had to make them all static which was annoying
    }

    pdftest.java:57: non-static variable this cannot be
    referenced from a static context
    PageNumberer pn = new
    PageNumberer();
    Is it basically that I can't use the new operator in
    my main function because main functions have to be
    static in java? What's the deal here?
    I had this app working as a Java SERVLET, so all i
    had to do to port it over was replace the doGet
    method with main and remove all references to servlet
    specific stuff, etc. Had to make all my methods
    static too so main could call them, but that's all
    fixed. And now the thing that makes it not compile is
    the new operator!?!?
    public class pdftest
         ....//private static members
              /* subClass to handle page numbering of pdf */
              class PageNumberer extends PdfPageEventHelper
         public static void main(String[] args)
              PageNumberer pn = new PageNumberer();
    ....//other methods, had to make them all static
    c which was annoying
    static class PageNumberer

  • How to make an object of inner class and use it ?

    Hi tecs,
    In my JSF application i have a need to make an inner member class in one of my bean class.
    How can i make the object of this class?(what should be the entry in faces-config)
    And there are text box and check box (in the JSP) associated with the elements of this inner class. What should be the coding in JSP so that elements in the JSP can be linked with the corresponding members of the inner class ?
    Plz help.
    Thnx in advance.

    Hi
    I am havin 10 text boxes in my application.
    But out of 10 , 3 will be always together(existence of one is not possible without the other two.)
    Now i want to create a vector of objects ( here object will consist of the value corresponding to these three boxes),there can be many elements in this vector.
    So i m thinking to make an inner class which have three String variables corresponding to these text boxes that exists together.
    What can b done ?

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

  • How can 1 make an object of user defined class immutable?

    Hi All,
    How can one make an object of user defined class immutable?
    Whats the implementation logic with strings as immutable?
    Regards,

    Hi All,
    How can one make an object of user defined class
    immutable?The simple answer is you can't. That is, you can't make the object itself immutable, but what you can do is make a wrapper so that the client never sees the object to begin with.
    A classic example of a mutable class:
    class MutableX {
        private String name = "None";
        public String getName() {
            return name;
        public void setName(String name) {
            this.name = name;
    }I don't think it's possible to make this immutable, but you can create a wrapper that is:
    class ImmutableX {
        private final MutableX wrappedInstance;
        public ImmutableX (String name) {
            wrappedInstance = new MutableX();
            wrappedInstance.setName(name);
        public String getName() {
            return wrappedInstance.getName();
        // Don't give them a way to set the name and never expose wrappedInstance.
    }Of course, if you're asking how you can make your own class immutable then the simple answer is to not make any public or protected methods that can mutate it and don't expose any mutable members.
    Whats the implementation logic with strings as
    immutable?
    Regards,I don't understand the question.

  • Accessing static context from instances...

    Hello,
    I'm confused with something. Accessing static elemnts or static methods from an instance is allowed. I think it shouldn't be allowed. Because static context is class-wide so objects shouldn't be able to access them.
    Am I wrong..?

    I find it confusing.. If something is class-wide then
    it should only be accessed by the class, not the
    instance of the class...That depends on the nature or purpose of the information. Static information or methods are a useful way of sharing information between instances of the same class, while still having that information protected from other classes. Other examples are constants which are used within each instance. Why should each instance have a separate copy of exactly the same constant?
    You could even argue that any method which does not need any instance information should be declared static, but it is not always necessary to make that distinction.
    Eclipse (mine at least :) ) gives a warning when you access a static
    method/variable 'through' an instance, telling you that you should access >the method/variable in a static way.This warning usually occurs if you call a static method in a non static way. For example, if you declare a class called MyClass with a static method myMethod() and you have an instance assigned to variable anInstance, you should call the method using MyClass.myMethod() instead of anInstance.myMethod().
    Graeme

  • How to make an object mutable?

    Can any one tell me how to make an object mutable?
    Following is Class X & Y?
    class Y
    public static void main(String arg[]) {
    X a1=new X();
    Object a=a1.get();
    System.out.println(a.toString());
    a1.set(a);
    System.out.println(a.toString());
    class X implements Serializable
    public Object get(){
    return new Object();
    public synchronized void set(Object o)
    o=null;
    In my class Y when i say
    a1.set(a);
    I want local Object a of main method should be nullified.
    Can it be possible if yes what is the way or code to be applied so that
    my next a.toString() statement will give me NullpointerException.

    Isn't it more accurate to say that object references are passed by value?
    OP -- Basically you can't to what you want to do. When you "pass an object" as a method parameter, what you're really passing is a copy of the reference that points to the object. You now have two refs pointing to the same object--one in the caller and one in the method being executed. Setting either of those refs to null does NOT affect the object itself, and does NOT affect the other ref. It just means that the ref that's been set to null no longer points to any object.
    If you want the called method to make a change that the caller can see, you need to either 1) return a value from the method, 2) encapsulate the object to be changed as a member of new class, or 3) pass the object to be changed as the single element of an array. I would STRONGLY recommend against (3) as a way to simulate pass by reference. Better to examine your design and determine whether (1) or (2) more closely matches what you're really trying to accomplish.

  • 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 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 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 cannot be referenced from a static context - ?

    Hi, i understand (kinda) what the error means
    i think its saying that i cannot call a non-static method "bubbleSort"
    from the static method main (correct?)
    but i dont know how to fix it...
    do i make bubbleSort
    public static void bubbleSort???
    C:\jLotto\dataFile\SortNumbers.java:80: non-static method bubbleSort(int[]) cannot be referenced from a static context
              bubbleSort( a ); //sort the array into ascending numbers
    my code:
    import java.io.*;
    import java.util.*;
    public class SortNumbers
         public static void main( String args[]) throws IOException
          int num;
              int a[] = new int[7]; //an array for sorting numbers
              File inputFile = new File("C:\\jLotto\\dataFile\\outagain.txt");
              File outputFile = new File("C:\\jLotto\\dataFile\\sortedNum.txt");
            BufferedReader br = new BufferedReader( new FileReader( inputFile ));
          PrintWriter pw = new PrintWriter( new FileWriter( outputFile ));
          String line = br.readLine();
          while( line != null ){//reads a single line from the file
             StringBuffer buffer = new StringBuffer(31);          //create a buffer
             StringTokenizer st = new StringTokenizer( line," "); //create a tokenizer
             while (st.hasMoreTokens()){
                        // the first 4 tokens are id,month,day,ccyy, no sorting needed
                        // so they are simply moved into the buffer
                        for (int i =1; i<5; i++){
                             num = Integer.parseInt(st.nextToken());
                             buffer.append( num );
                             buffer.append( "|");
                        //tokens 5 to 11 need to be sorted into acending order
                        //so read tokens 5 to 11 into an array for sorting
                        for (int i =0; i<7; i++){
                             a[i] = Integer.parseInt(st.nextToken());
                     bubbleSort( a ); //sort the array into ascending numbers
                      //the array is sorted so read array back into the buffer
                      for ( int i = 0; i < a.length; i++ ){
                           buffer.append( a[ i ] );
                           buffer.append(  "|" ) ;
                   }//end of while st.hasMoreTokens
             //then write out the record from the stringBuffer
             pw.println( buffer );
             line = br.readLine();
          }//end of while != null
              br.close();
              pw.close();
         }//end of static main
       // sort the elements of an array with bubble sort
       public void bubbleSort( int b[] )
          int swapMade = 0; //if after one pass, no swaps were made - exit
          for ( int pass = 1; pass < ( b.length - pass) ; pass++ ) // passes reduced for speed
              for ( int i = 0; i < b.length - 1; i++ ) // one pass
                  if ( b[ i ] > b[ i + 1 ] )            // one comparison
                      swap( b, i, i + 1 );              // one swap
                      swapMade = 1;
                  }  // end of if
               } //end of one pass
             if (swapMade == 0) pass = 7; //no swaps, so break out of outter for loop
          }//end of passes, end of outter for loop
       }//end of bubblesort method
       // swap two elements of an array
       public void swap( int c[], int first, int second )
          int hold;  // temporary holding area for swap
          hold = c[ first ];
          c[ first ] = c[ second ];
          c[ second ] = hold;
       }   //end of swap
    }//end of class SortNumbers

    Static means
    when u run the program (a class), there is only one variabel / type in memory.
    ex static int a; //assume it's inside the aStaticClass
    mean no wonder how many u create object from this class, variabel a only have 1 in memory. so if u change a (ex a=1;) all instance of this aStaticClass will effected (because they share the same variabel).
    Try to read more at :
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
    I hope this will help you....happy new year
    yonscun

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

  • Implementing Custom Event - non-static referencing in static context error

    Hi,
    I'm implementing a custom event, and I have problems adding my custom listeners to objects. I can't compile because I'm referencing a non-static method (my custom addListener method ) from a static context (a JFrame which contains static main).
    However, the same error occurs even if I try to add the custom listener to another class without the main function.
    Q1. Is the way I'm adding the listener wrong? Is there a way to resolve the non-static referencing error?
    Q2. From the examples online, I don't see people adding the Class name in front of addListener.
    Refering to the code below, if I remove "Data." in front of addDataUpdatelistener, I get the error:
    cannot resolve symbol method addDataUpdateListener (<anonymous DataUpdateListener>)
    I'm wondering if this is where the error is coming from.
    Below is a simplified version of my code. Thanks in advance!
    Cindy
    //dividers indicate contents are in separate source files
    //DataUpdateEvent Class
    public class DataUpdateEvent extends java.util.EventObject
         public DataUpdateEvent(Object eventSource)
              super(eventSource);
    //DataUpdateListener Interface
    public interface DataUpdateListener extends java.util.EventListener
      public void dataUpdateOccured(DataUpdateEvent event);
    //Data Class: contains data which is updated periodically. Needs to notify Display frame.
    class Data
    //do something to data
    //fire an event to notify listeners data has changed
    fireEvent(new DataUpdateEvent(this));
      private void fireEvent(DataUpdateEvent event)
           // Make a copy of the list and use this list to fire events.
           // This way listeners can be added and removed to and from
           // the original list in response to this event.
           Vector list;
           synchronized(this)
                list = (Vector)listeners.clone();
           for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
               DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
               // Make a call to the method implemented by the listeners
                  // and defined in the listener interface object.
                  listener.dataUpdateOccured(event);
               System.out.println("event fired");
    public synchronized void addDataUpdateListener(DataUpdateListener listener)
         listeners.addElement(listener);
      public synchronized void removeDataUpdateListener(DataUpdateListener listener)
         listeners.removeElement(listener);
    //Display Class: creates a JFrame to display data
    public class Display extends javax.swing.JFrame
         public static void main(String args[])
              //display frame
              new Display().show();
         public Display()
         //ERROR OCCURS HERE:
         // Non-static method addDataUpdateListener (DataUpdateListener) cannot be referenced from a static context
         Data.addDataUpdateListener(new DataUpdateListener()
             public void dataUpdateOccured(DataUpdateEvent e)
                 System.out.println("Event Received!");
    //-----------------------------------------------------------

    Calling
        Data.someMethodName()is referencing a method in the Data class whose signature includes the 'static' modifier and
    might look something like this:
    class Data
        static void someMethodName() {}What you want is to add the listener to an instance of the Data class. It's just like adding
    an ActionListener to a JButton:
        JButton.addActionListener(new ActionListener()    // won't work
        JButton button = new JButton("button");           // instance of JButton
        button.addActionListener(new ActionListener()     // okay
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    public class EventTest extends JFrame
        Data data;
        JLabel label;
        public EventTest()
            label = getLabel();
            data = new Data();
            // add listener to instance ('data') of Data
            data.addDataUpdateListener(new DataUpdateListener()
                public void dataUpdateOccured(DataUpdateEvent e)
                    System.out.println("Event Received!");
                    label.setText("count = " + e.getValue());
            getContentPane().add(label, "South");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(300,200);
            setLocation(200,200);
            setVisible(true);
        private JLabel getLabel()
            label = new JLabel("  ", JLabel.CENTER);
            Dimension d = label.getPreferredSize();
            d.height = 25;
            label.setPreferredSize(d);
            return label;
        public static void main(String[] args)
            new EventTest();
    * DataUpdateEvent Class
    class DataUpdateEvent extends java.util.EventObject
        int value;
        public DataUpdateEvent(Object eventSource, int value)
            super(eventSource);
            this.value = value;
        public int getValue()
            return value;
    * DataUpdateListener Interface
    interface DataUpdateListener extends java.util.EventListener
        public void dataUpdateOccured(DataUpdateEvent event);
    * Data Class: contains data which is updated periodically.
    * Needs to notify Display frame.
    class Data
        Vector listeners;
        int count;
        public Data()
            listeners = new Vector();
            count = 0;
            new Thread(runner).start();
        private void increaseCount()
            count++;
            fireEvent(new DataUpdateEvent(this, count));
        private void fireEvent(DataUpdateEvent event)
            // Make a copy of the list and use this list to fire events.
            // This way listeners can be added and removed to and from
            // the original list in response to this event.
            Vector list;
            synchronized(this)
                list = (Vector)listeners.clone();
            for (int i=0; i < list.size(); i++)
                // Get the next listener and cast the object to right listener type.
                DataUpdateListener listener = (DataUpdateListener) list.elementAt(i);
                // Make a call to the method implemented by the listeners
                // and defined in the listener interface object.
                listener.dataUpdateOccured(event);
            System.out.println("event fired");
        public synchronized void addDataUpdateListener(DataUpdateListener listener)
            listeners.addElement(listener);
        public synchronized void removeDataUpdateListener(DataUpdateListener listener)
            listeners.removeElement(listener);
        private Runnable runner = new Runnable()
            public void run()
                boolean runit = true;
                while(runit)
                    increaseCount();
                    try
                        Thread.sleep(1000);
                    catch(InterruptedException ie)
                        System.err.println("interrupt: " + ie.getMessage());
                    if(count > 100)
                        runit = false;
    }

  • Compiler thinks getDeclaredFields method is in a static context

    Hi folks,
    I have the following lines of code at the beginning of a non-static method ;
    public void streamOutput(Object objectToStream, boolean autoFlush)
    Class objectClass = objectToStream.getClass();
    Field[] fieldArray = Class.getDeclaredFields();
    When using javac to compile this code I get the following error ;
    Can't make static reference to method java.la
    ng.reflect.Field getDeclaredFields()[] in class java.lang.Class.
    Field[] fieldArray = Class.getDeclaredFields();
    ^
    The thing is that I can't see how javac thinks that the method is being called within a static context. The method is non-static, the containing class in non-static, and I even have a reference to 'this' later on inside the method which the compiler accepts ( which it surely wouldn't if I was working within a static context ).
    Any ideas what is wrong ?

    The line "Class.getDeclaredFields();" is written as if the method getDeclaredFields() is a static method. It isn't. You have to use an instance of some class. Maybe what you need is objectClass.getClass().getDeclaredFields();

Maybe you are looking for

  • A600 setup with Verizon TV

    I wanted to start this subject to see if any end users have gone from Direct TV to Verizon Cable TV successfully. I had a customer that was sold the Motorola QIP2500-3 Set Top Terminal. After going through Windows media center setup the customer was

  • WRT350N - Transfer speed via Storage link

    I have always been curious what the transfer speed others get while using a USB 2.0 hard drives on their WRT350N. Obviously there is going to be a drop in transfer speed using storage link but 2-3 Megabyte seems slower then I would expect.   I don't

  • EDI to XML Translator for Java

    Anyone know about an EDI to XML translator which can be called from a Java program ? I already know about OBOE and XEDI Thanks!

  • Abap Program Check

    hi all, i need to do the following checks in any report program 1. how to check a parameter starting with p_ or not ?  2. how to check a data variable starting with v_ or not  ? 3. how to giv identification to the user if he had used any comments in

  • Help an old man please

    My father-in-law has spent the last 20 years compiling his memoirs and at the age of 87 he hasn't done a bad job.  I'm trying to use ibook author to create a version the family can read on ipads etc however his book has a number of diffences across t