简体   繁体   中英

Setting value to abstract private field from subclass

I would like to know about the most efficient way to set a value to an abstract private field from a subclass. So, for example, have a field called itemCost , then I would like to initialize its value to 200 in the subclass.

There is no such abstract private field in Java. Only classes and methods can be abstract. But to emulate an abstract field, I believe there are at least two good methods:

  • Method (1) : Define an uninitialized final field in the superclass. And initialize it in the child class. This is more suitable to constant (primitive) variables and having the variable initialized in the constructor is perfectly fine. It will also work well with complex types of course (class instances with mutable content, instead of primitive types).
  • Method (2) : Define an abstract setter for the field to force the subclass to implement/redefine this method and do the specific initializations. This is more suitable for varying field content but there is no guarantee that the field will be correctly initialized by all subclasses. This becomes implementation-dependent.

Method (1)

abstract class MySuperClass {
    final int itemCost;
    
    protected MySuperClass(int _itemCost) {
        this.itemCost = _itemCost;
    }
}

class MySubClass extends MySuperClass {
    public MySubClass() {
        super(200);
    }
    
    public MySubClass(int itemCost) {
        super(itemCost);
    }
}

If you do not call super(itemCost) you will get a compiler error. So this is very enforcing.

Method (2)

abstract class MySuperClass {
    int itemCost;
    
    protected MySuperClass() { }
    
    abstract void setItemCost();
    abstract void setItemCost(int _itemCost);
}

class MySubClass extends MySuperClass {
    public MySubClass() {
        setItemCost();
    }
    
    public MySubClass(int itemCost) { 
        setItemCost(itemCost);
    }

    @Override
    final void setItemCost() {
        this.itemCost = 200;
    }
    
    @Override
    final void setItemCost(int _itemCost) {
        this.itemCost = _itemCost;
    }        
}

If you are interested in modifying the value after instantiation and if the child class is correctly implemented, then it is a fine solution. But it is a more verbose, less intuitive and error-prone solution.

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