简体   繁体   中英

Abstract class in Java with global variables aren't setting?

I've got 2 classes setup, both extending a Module class. I'm trying to set 2 integers in one of them and using 2 integers in the other. However when I execute everything, it does get set (I know because of debugging) but when the method for 'printing' runs, it's still 0.

I don't know what I'm doing wrong though.

Module Class:

public abstract class Module {
     protected int min, max;
}

Foo1:

public class Foo1 extends Module {
     public void setMinMax(){
         min = 2;
         max = 5;
     }
}

Foo2:

public class Foo2 extends Module {
     public void printMinMax(){
         System.out.print("Min: " + min + " Max: " + max);
     }
}

You have 2 instances of 2 different classes. One instance of a Foo1 , with its own min / max , and one instance of a Foo2 , again with its own min / max .

Note that your Foo class provides the fields, and each time you instantiate a derived instance (of Foo1 or Foo2 ), you'll get a new class with a new set of fields (including those derived from the base class)

When you set one instance, it has no effect on another instance. Each instance has it's own fields. Most likely what you imagined was

public abstract class Module {
     protected static int min, max;
}

This way the fields will be shared between all instances of Module . You should only set these field from a static method, ideally on Module

However, I would avoid doing this, or using mutable static fields whenever possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM