简体   繁体   English

Java中具有全局变量的抽象类未设置吗?

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

I've got 2 classes setup, both extending a Module class. 我有2个类的设置,都扩展了Module类。 I'm trying to set 2 integers in one of them and using 2 integers in the other. 我试图在其中一个中设置2个整数,在另一个中使用2个整数。 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. 但是,当我执行所有操作时,它的确设置了(我知道是由于调试),但是当运行“打印”方法时,它仍然为0。

I don't know what I'm doing wrong though. 我不知道我在做什么错。

Module Class: 模块类别:

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

Foo1: Foo1:

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

Foo2: Foo2:

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

You have 2 instances of 2 different classes. 您有2个不同类的2个实例。 One instance of a Foo1 , with its own min / max , and one instance of a Foo2 , again with its own min / max . 一的一个实例Foo1 ,有自己的min / max和的一个实例Foo2有自己的, 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) 请注意,您的Foo类提供了字段,并且每次实例化( Foo1Foo2 )派生实例时,您都会获得一个具有新字段集(包括从基类派生的字段)的新类。

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 . 这样,字段将在Module所有实例之间共享。 You should only set these field from a static method, ideally on Module 您只能通过静态方法设置这些字段,最好是在Module

However, I would avoid doing this, or using mutable static fields whenever possible. 但是,我将避免这样做,或者尽可能避免使用可变的静态字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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