Saturn
Saturn

Reputation: 18139

Is there any difference when a field is static or not when it belongs to an abstract class?

public abstract class Test {

    private static int value = 100;

}

And

public abstract class Test {

    private int value = 100;

}

Since Test is abstract, it can't be instantiated, and therefore it doesn't make any difference whether value is static or not, right?

Is there any difference when a field is static or not when it belongs to an abstract class?

Upvotes: 1

Views: 54

Answers (3)

kajacx
kajacx

Reputation: 12939

Yes, there is. Even thou your class is abstract, it can have non-abstract non-static methods working with non-static private fields. It is usefull sometimes.

Dummy exaple:

Consider following: you want to hold one integer and give everyone the ability to change it, but you dont want them to set negative values, or values bigger then 15, but the condition isn't known (in general) by everyone, so you want to ensure that when someone sets incorect value, it gets fixed automaticly.

Here is one possible solution:

abstract class MyInt {

    private int myInt;

    public int getMyInt() {
        return myInt;
    }

    public void setMyInt(int i) {
        myInt = checkMyInt(i);
    }

    protected abstract int checkMyInt(int i);
}

Now you can inplement any logic in checkMyInt() and hand over the instance declared as MyInt

pastebin exaplme

PS: this probably isnt the best solution and i would use interfaces here, but as an example it is enought i hope

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691635

Abstract classes can't be instantiated directly. But the whole point of abstract classes is to have subclasses that are instantiated:

public abstract class Test
    protected int value;
}

public class TestImpl extends Test {
    public TestImpl(int value) {
        this.value = value;
    }
}

In the above example, each instance of TestImpl (and thus of Test) has its own value. With a static field, the field is scoped to the Test class, and shared by all instances.

The difference between static and non-static fields is thus exactly the same as with any other non-abstract class.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

An abstract class is a normal (base) class, just declared to be missing some things, like abstract methods.

So there is definite a difference.

Upvotes: 0

Related Questions