Is CLASS VARIABLE changed?

I have two classes in same package. I defined a class variable 'no_of_gear' and later changed its value. The changed value
works in the same class but does not work in sub-class in same package.
class ClassVar {
     static int no_of_gear = 5;
     public static void main(String[] args) {
          System.out.println(no_of_gear); //Prints 5
          ClassVar cv = new ClassVar();
          System.out.println(cv.no_of_gear); //Prints 5
          cv.no_of_gear = 8;
          System.out.println(cv.no_of_gear); //Prints 8
          System.out.println(no_of_gear); //Prints 8
}Here is sub-class in same package.
class ClassVarAcc extends ClassVar {
     public static void main(String[] args) {
          System.out.println(no_of_gear); //Prints 5
          ClassVar cv = new ClassVar();
          System.out.println(cv.no_of_gear); //Prints 5
}Java Tutorial by SUN reveals that if class variable is changed by one object it is changed for all objects of that class. But, my code does not support the statement. Please, Can you clarify it?

Yes i do but not to the extent you are pointingto.
Why can't you just say you don't when you don't?
Can you answer in details?Look at your super class
class ClassVar {
static int no_of_gear = 5;
public static void main(String[] args) {
     System.out.println(no_of_gear); //Prints 5
     ClassVar cv = new ClassVar();
          System.out.println(cv.no_of_gear); //Prints 5
     cv.no_of_gear = 8;
          System.out.println(cv.no_of_gear); //Prints 8
     System.out.println(no_of_gear); //Prints 8
}In what method does the value of no_of_gear change?
Now look at the sub-class. Do you see yourself
calling this method?OH my dear. It is class variable that can be accessed directly (unlike instance variables) without the need of some method to change its value.
Here i change it. (Remeber: a copy of instance variable is passed to an instance of some class but no copy of class variable is passed to an instance of that class)
     cv.no_of_gear = 8;
     System.out.println(cv.no_of_gear); //Prints 8
Here it works fine.
     System.out.println(no_of_gear); //Prints 8
But, why does not it work in sub-class?

Similar Messages

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

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • Private or Protected access for super class variables

    What is the best practice...
    Assume there is a class hierachy like
    Person (Super class) / StaffMember/ Professor (Sub class)
    1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
    Ex:-
    public class Person {
    private String empNo;
    public Person (String empNo) {
    this.empNo = empNo;
    public class Professor extends Person {
    private String ........;
    private int ...........;
    public Professor (String pEmpNo) {
    super(pEmpNo);
    OR
    2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
    Ex:-
    public class Person {
    protected String empNo;
    public Person () {
    public class Professor extends Person {
    String ........;
    int ...........;
    public Professor (String empNo) {
    this.empNo = empNo;
    Thank you...

    i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures

  • Class variables outside of method scope?

    Hey guys,
    I have 3 text fields. 2 are meant for input and 1 for output. I want to take the float values from the 2 input text fields and do some math on them and then output the results in the output text field. Heres the problem, I need to make sure that both the text fields have some value stored in them. Well, that's not the problem, the problem is that the method only seems to be able to check the 'textField' parameter thats passed into the method pasted below. Whenever I try to run checks on the textfield class variables specifically, it doesn't seem to pick up on any of the text field's value changes or anything... Any ideas?
    I have the following:
    - (void)textFieldDidEndEditing:(UITextField *)textField {
    if([heightText.text length] > 0 && [weightText.text length] > 0) {
    bmiText.text = @"hi";
    else if([textField.text length] > 0) {
    bmiText.text = @"atleast this works";
    else {
    bmiText.text = @"";

    Here is the .h file:
    @interface BMIViewController : UIViewController {
    //...some other variables
    UITextField *heightText;
    UITextField *weightText;
    @property (nonatomic, retain) UITextField *heightText;
    @property (nonatomic, retain) UITextField *weightText;
    Here is the .m file:
    @implementation BMIViewController
    @synthesize weightText, heightText;
    //...some code...
    - (void)textFieldDidEndEditing:(UITextField *)textField {
    if([heightText.text length] > 0 && [weightText.text length] > 0) {
    bmiText.text = @"hi";
    else if([textField.text length] > 0) {
    bmiText.text = @"atleast this works";
    else {
    bmiText.text = @"";

  • Final Variable changed on runtime...

    Hello, I recently did a test with my program, which involved the use of 32 clients connecting to a server from a single application, however on runtime, the some final variables had their values changed, for example
    private static final Point point1 = new Point(100,100);
    had changed values to 480,360, and the default Point in my Point class had changed it's value from 0,0 to another value as well. How is this possible? The only methods used on the finalized point was equals/distance, which both do not affect the private fields of point, yet they were changed after logging in about 29 clients or so.
        public int distance(Point p2)
            return Math.max(Math.abs(p2.x - x), Math.abs(p2.y - y));
        public boolean equals(Point p)
            return (p.x == x && p.y == y);
        public boolean equals(Object obj)
            if (obj instanceof Point)
                return (((Point) obj).x == x && ((Point) obj).y == y);
            return false;
        }And here is where they are used
        private static final Point mine = new Point(167, 105);...
                        if (!cLoc.equals(mine))
                            if (cLoc.distance(mine) <= 18)
                                Player.jump(mine);
                                Player.Mine();
                                lastMineTime = 0;
                        }Any idea why this happened?

    Sorry, I was not clear enough
    Here is my Point class
    http://pastebin.com/m6075a9d8
    Now, after logging on about 38 clients (about 204 threads lol....), the constant fields get changed, for example within the point class, the "DEFAULT" gets changed to a random variable (which never happened before when logging on 10-20 only)
    Same goes for my other constant variables, their values get changed.
    For Example these Points:
        private static final Point sellPoint = new Point(417, 357);
        private static final Point mineExit = new Point(156, 90);
        private static final Point mineExitPoint = new Point(53, 399);
        private static final Point mineEntrance = new Point(45, 397);
        private static final Point mine = new Point(167, 105);Would get changed to something totally different, while the only functions used on those points are equals/distance.
    Here is an image of the Point instance while in debug mode:
    http://img193.imageshack.us/img193/6774/javaerror.jpg
    As you can see , mineExit takes the place of mineExitPoint (however I don't know why..), and mineExitPoint remains the same.....
    Another image:
    http://img6.imageshack.us/img6/9088/javaerror2.jpg
    Edit: Could it be the fact that around 30 threads are checking the same static/final variable at once?
    Edited by: Naki on Jul 1, 2009 6:43 PM

  • Class Variables

    So I'm writing a Class in AS2 and I'm having problems in this
    one method. I have a method that uses a Tween class and I want to
    use the onMotionFinished method of the Tween class to change a
    class scope variable, but I seem to loose scope once I'm inside the
    onMotionFinished method. I'll attach the method code, but basically
    when I trace "this" inside the onMotionFinished, I get the Tween,
    and even tracing this.obj._parent doesn't give the class instance,
    it gives level that the tweened object was created on. "_state" is
    the class level variable I'm trying to change, but when I trace it
    from within onMotionFinished I get "undefined". Any suggestions to
    getting back to the class level?

    BeniRose,
    > Actually I figured it out just a few minutes after
    posting! I
    > found it in some old code I had from a previous job. At
    > the begging of the method I include:
    >
    > var me = this;
    That will certainly do it (and of course, that "me" can be
    named
    whatever you like; it can be classRef, thisInstance, me, or
    whatever makes
    sense to you). Another approach is to use the Delegate class,
    which
    features a static create() method that lets you re-route
    scope:
    unblur.onMotionFinished = Delegate.create(
    this,
    function() {
    _state = "shown";
    Note the scope (via "this") as the first parameter, and the
    function as
    the second parameter. You're basically doing this:
    Delegate.create(scope,
    function);, and the function performs in the scope specified.
    Since you're getting into AS2 classes, I encourage you to
    use strong
    typing everywhere you can. It's a good habit to get in to,
    because the
    strong typing gives you better error messages and sometimes
    helps with code
    completion (note the :Void):
    unblur.onMotionFinished = Delegate.create(
    this,
    function():Void {
    _state = "shown";
    You'll have to import the Delegate class at the top of your
    custom class
    in order to use it.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Class variable

    Hi everybody,
    In the following code, I want to set the class variable fileChanged to true after I called CheckFileThread class. It seems since CheckFileThread is a thread, after the timer is cancelled I won't come back to point1. How can I set the class variable thru other class?
    Any help is greatly appreciated. Thanks.
    import java.util.*;
    import java.lang.Thread;
    class testClass6
        private static boolean fileChanged = false;
        public static void main(String[] Args)
         testClass6 t = new testClass6();
         t.execute();
        public void execute()
         new CheckFileThread();     
    //point1
    // I want to check when the class variable: fileChanged becomes true.
         if (!fileChanged)
             System.out.println("Class variable fileChanged is false.");
         else
             System.out.println("Class variable fileChanged is now true.");
        class CheckFileThread
         CheckFileThread()
             Calendar rightNow = Calendar.getInstance();
             Date time = rightNow.getTime();
             System.out.println("This is time: " + time);
             new Reminder3(time);
         class Reminder3
             Timer timer;
             public Reminder3(Date time)
              timer = new Timer();
              timer.schedule(new RemindTask3(), time, 1*1000);
             class RemindTask3 extends TimerTask
              int a = 3;
              public void run()
                  if (a > 0)
                       System.out.println("I'm inside run. This message will print out every sec!");
                       a--;               
                  else
                       System.out.println("Times up!");
                       timer.cancel();
                       System.out.println("Setting the class variable to true...");
                       fileChanged = true;
              }//endof m:run
             }//endof class:RemindTask3
         }//endof class:Reminder3
        }//endof class: CheckFileThread
    } //endof class: testClass6

    Thanks for the reply. That's what I'm trying to do:
    method: execute() creates many theards and they start running. Now at one point I have to check if an input file changed since last modification. If NO, nothing changes; if YES, I have to stop all running threads and create new threads. The method that checks if input file has changed or not, it's a thread on its own that runs every 24 hours. It's a seperate class inside execute() but it seems I can't set the class variable: fileChanged thru that class. Below is a small code that says what I am trying to do. Sorry if I made you confused!
    import java.util.*;
    import java.lang.Thread;
    class testClass6
        private volatile static boolean fileChanged = false;
        public static void main(String[] Args)
         testClass6 t = new testClass6();
         t.execute();
        public void execute()
    // Creates threads and they are running.
    // Lot's of threads are running, I check if the class variable: fileChanged is true or not every 24 hours. If it's
    // true, I have to stop all running threads.
         new CheckFileThread();     
         if (!fileChanged)
             System.out.println("Class variable fileChanged is false.");
         else
             System.out.println("Class variable fileChanged is now true thru another class.");
    // It's a thread that runs every 24 hours
        class CheckFileThread
         CheckFileThread()
    // Here check to see if the file changed since last modification, if yes, set fileChanged = true
         }//endof class: CheckFileThread
    } //endof class: testClass6

  • Functions triggered on variable change

    Hi there!
    It's surely something quite easy, but couldn't find exactly
    what I wanted; it must be related to the eventListener thing, but
    don't know how to do it:
    I'd like several movie clips to react (each one in its own
    way) when a variable changes; say I've got a website that needs to
    be editable when the var _root.vAdmin = "yes" and not when the
    latter equals "no"; so I need multiple functions situated anywhere
    to be triggered when the variable _root.vAdmin changes; any idea?
    Thanks in advance!

    seems like this is what you need. look into EventDispatcher
    or AsBroadcaster classes
    tutorial:
    http://www.kirupa.com/developer/actionscript/eventdispatcher.htm

  • A variable changing itself

    Hello,
    Suppose I have a class which has in its scope an instance of itself. If one of this class' methods changes the instance, and this method is called from the instance itself, what will happen? When I say "changing", I mean allocating a new instance to the variable and not changing the instance's attributes. I'm afraid to try executing a sample program, because there's a risk in such programs (although I suppose Java's protections will prevent hazard operations like this and throw an exception).
    Thanks.

    Hello,
    Suppose I have a class which has in its scope an
    instance of itself.You mean, an instance has an attribute that contains another instance of the same class? That's how to design a memory leak.
    If one of this class' methods
    changes the instance, and this method is called from
    the instance itself, what will happen???? The mothod will be called on the specified instance. I don't get you.
    When I say
    "changing", I mean allocating a new instance to the
    e variable and not changing the instance's
    attributes. I'm afraid to try executing a sample
    program, because there's a risk in such programs
    (although I suppose Java's protections will prevent
    hazard operations like this and throw an exception).
    Thanks.Simply do it - I don't really get you, so you better try it yourself. An exception does not break anything on your computer - why are you afraid of it?

  • Function Modules / Classes to change cProject item

    Hello,
    I'am searching for function modules or classes to change the cProject item.
    Ich want to change some fields in the task of cProject. Can everbody help me?
    Kind regards Axel

    Dear Thomas,
    I've following requirements:
    - Automated Creation of a cFolders folder structure/hierarchy from a structured uploaded from an excel file
      from R/3 ABAP program
    - Search for a particular document in cFolders using R/3 ABAP program
    Would it be possible to do the above tasks using the BAPIs mentioned in your post.
    Thanks.

  • Assign a value to class variable

    I want to define a class variable in class. And I want all subclasses of that class ot have a different value for that class variable. How can I do that?
    public class BaseClass {
      public static String tableName = "";
    }Now if I have a ClassA and I want to assign a value like this :
    public class ClassA extends BaseClass {
      tableName = "location";
    } I got an error message.
    I can move it in a static initializer block but then it will only work when the class is loaded. In my case its possible i want to get this value without loading the class.
    Ditto if i move it to constructor.
    Any input? Thanks

    Are you saying that if i have 2 classes ClassA and
    ClassB inherited from BaseClass, then both are
    sharing the same copy of 'tableName' staticvariable?
    If yes then I should go with an instance variable.No, I am saying that you can easily declare a
    tablName in A and another tableName in B.
    A.tableName will be shared between all the instances
    s of A. B.tableName will be shared between all the
    instances of B. And BaseClass.tableName is
    irelevant. I think you try to use
    BaseClass.tableName as some kind of template for
    sub-classes, but this does not happen: you need to
    declare tableName again and again in each subclass.
    IThanks for clarifying. Each class needs to have a variable "tableName" and it needs to have one copy of this variable for all of that class's objects. 2 classes will not have the same value of this tableName variable.
    Thats why I was defining it as static variable. And I define it in BaseClass so that I dont have to define it again in each subclass.
    Is there any better way? Thanks

  • Unbound Class Variable Error

    Hi All,
    I am doing a webdynpro application. while deploying, it gives me an error
    "Unbound class Variable:'KMC_LIBS/bc.srf.framework_api.jar'.
    What is this error?
    Regards,
    Divya

    Hi,
    A Classpath Variable is just a variable which points to a directory in your file system.
    Useful when 1st developer has external jars on path1 and 2nd developer has external jars on path2 (the two paths are different) and the developers want to prevent classpath issues.
    In NWDS go to:
    Window -> Preferences -> Java -> Classpath Variables and check if 'KMC_LIBS' points to a directory.
    Also, you can delete this entry from your project's classpath and add the file 'bc.srf.framework_api.jar'' manually (without classpath variable).
    Regards,
    Omri

  • [svn:fx-trunk] 11454: ASyncList class ASDoc change: added explicit warning about the lack of support for re-inserting pending items .

    Revision: 11454
    Author:   [email protected]
    Date:     2009-11-04 18:17:33 -0800 (Wed, 04 Nov 2009)
    Log Message:
    ASyncList class ASDoc change: added explicit warning about the lack of support for re-inserting pending items.
    QE notes:
    Doc notes:
    Bugs:
    Reviewer:
    Tests run:
    Is noteworthy for integration:
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/framework/src/mx/collections/AsyncListView.as

  • Create an instance of my class variable

    Hello all,
    I'm a newbie to iPhone/iPad programming and am having some trouble, I believe the issue is that I'm not creating an instance of my class variable.  I've got a class that has a setter and a getter, I know about properties but am using setters and getters for the time being.  I've created this class in a View-based application, when I build the program in XCode 3.2.6 everything builds fine.  When I step through the code with the debugger there are no errors but the setters are not storing any values and thus the getters are always returning 0 (it's returning an int value).  I've produced some of the code involved and I was hoping someone could point out to me where my issue is, and if I'm correct about not instantiating my variable, where I should do that.  Thanks so much in advance.
    <p>
    Selection.h
    @interface Selection : NSObject {
      int _choice;
    //Getters
    -(int) Choice;
    //Setters
    -(void) setChoice:(int) input;
    Selection.m
    #import "Selection.h"
    @implementation Selection
    //Getters
    -(int)Choice {
      return _choice;
    //Setter
    -(void)setChoice:(int)input{
              _choice = input;
    RockPaperScissorsViewController.m
    #import "RockPaperScissorsViewController.h"
    @implementation RockPaperScissorsViewController
    @synthesize rockButton, paperButton, scissorsButton, label;
    //@synthesize humanChoice, computerChoice;
    -(void)SetLabel:(NSString *)selection{
              label.text = selection;
    -(IBAction)rockButtonSelected {
    //          [self SetLabel:@"Rock"];
              [humanChoice setChoice:1];
    </p>
    So in the above code it's the [humanChoice setChoice:1] that is not working.  When I step through that portion with the debugger I get no errors but when I call humanChoice.Choice later on in the code I get a zero.
    -NifflerX

    It worked, thank you so much.  I put
    humanChoice = [[Selection alloc]init];
    In viewDidLoad and it worked like a charm.  Thank you again.
    -NifflerX

Maybe you are looking for

  • Anyone else.....Mini 1000 - 1154nr "Internal Short"?

    We're on the second netbook from Verizon.  The first one when you picked it up by a corner the sound got really scratchy and the volume went way down. You could get it back to normal by flexing the base or sometimes moving the screen up and down.  Mi

  • [CS4 - JS]Export stories and "object is invalid" error

    Hello all, I need a javascript script that exports all the stories of a document to .icml files. At the moment I've come to a function like this: function exportICML(myDoc, path) {         var stories = myDoc.stories; for (var i = 0; i < stories.leng

  • Crystal report integration with CRM

    Hi, Guru: I would like to check with you. I need show a demo to integrate crystal reports with our CRM product. I know for CRM mobile (mobile system maintenance), we could have this option. however, my requirement is to seek any other options to inte

  • Java Web Start and JasperReports

    Hi all, I am trying to get jasper reports (search www.sourceforge.net for jasperreports) to work with Java web Start. I have a problem in that jasper reports cannot find the SAX2 parser in the jar file even though its there. Jasper requires one to se

  • Library Link Errors

    My links on my library items are malfunctioning. Even though the links appear correct in the code and design views, and function properly at times, out of nowhere an extra "html" is inserted in the URL, causing the links to be broken. Can anyone help