MrDikke
MrDikke

Reputation: 119

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);
     }
}

Upvotes: 0

Views: 1439

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272297

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)

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 0

Related Questions