简体   繁体   English

将值设置为从子类中抽象私有字段

[英]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.因此,例如,有一个名为itemCost的字段,那么我想在子类中将其值初始化为 200。

There is no such abstract private field in Java. 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.方法(1) :在超类中定义一个未初始化的final field And initialize it in the child class.并在子 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.方法(2) :为字段定义一个abstract setter ,强制子类实现/重新定义该方法并进行具体的初始化。 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.如果你不调用super(itemCost)你会得到一个编译器错误。 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.如果您有兴趣在实例化后修改值,并且子 class 正确实现,那么这是一个很好的解决方案。 But it is a more verbose, less intuitive and error-prone solution.但它是一种更冗长、更不直观且容易出错的解决方案。

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

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