initialize fileds in interfaces

探讨了在Java接口中使用非常量表达式初始化字段的方法,通过实例展示了如何在接口中定义并初始化Random类型的变量,以及由此产生的各种随机数值。

Fields defined in interfaces cannot be “blank finals,” but they can be initialized with non-constant expressions. For example:

// interfaces/RandVals.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Initializing interface fields with
// non-constant initializers

import java.util.*;

public interface RandVals {
  Random RAND = new Random(47);
  int RANDOM_INT = RAND.nextInt(10);
  long RANDOM_LONG = RAND.nextLong() * 10;
  float RANDOM_FLOAT = RAND.nextLong() * 10;
  double RANDOM_DOUBLE = RAND.nextDouble() * 10;
}

test above code:

// interfaces/TestRandVals.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class TestRandVals {
  public static void main(String[] args) {
    System.out.println(RandVals.RANDOM_INT);
    System.out.println(RandVals.RANDOM_LONG);
    System.out.println(RandVals.RANDOM_FLOAT);
    System.out.println(RandVals.RANDOM_DOUBLE);
  }
}
/* Output:
8
-32032247016559954
-8.5939291E18
5.779976127815049
*/

Knowledge:

The fields are not part of the interface. The values are stored in the static storage area for that interface.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/interfaces/RandVals.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/interfaces/TestRandVals.java

import java.util.ArrayList; import java.util.List; /* ---------- 1. Interface ---------- */ interface Payable { double calculatePayment(); } /* ---------- 2a. Employee class ---------- */ class Employee implements Payable { /* TODO: add fields: String name double hourlyRate int hoursWorked */ public Employee(String name, double hourlyRate, int hoursWorked) { /* TODO: initialize the fields */ } @Override public double calculatePayment() { /* TODO: return hourlyRate * hoursWorked */ return 0; // placeholder } @Override public String toString() { /* TODO: return string in format: "Employee: <name> <hoursWorked> hrs @ $<hourlyRate>" */ return ""; // placeholder } } /* ---------- 2b. Invoice class ---------- */ class Invoice implements Payable { /* TODO: add fields: String item double unitPrice int quantity */ public Invoice(String item, double unitPrice, int quantity) { /* TODO: initialize the fields */ } @Override public double calculatePayment() { /* TODO: return unitPrice * quantity */ return 0; // placeholder } @Override public String toString() { /* TODO: return string in format: "Invoice: <quantity> <item> @ $<unitPrice>" */ return ""; // placeholder } } /* ---------- 3. PayrollApp ---------- */ public class PayrollApp { public static void main(String[] args) { Payable[] payroll = new Payable[2]; /* TODO: 1. Add at least one Employee and one Invoice to the array. 2. Loop through the array and print each Payable object along with its calculated payment using polymorphism. Example output: Employee: Alice 40 hrs @ $25.6 -> $1024.00 Invoice: 3 Laptop @ $800.0 -> $2400.00 */ } }补充代码
最新发布
12-08
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream. When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; private void readObjectNoData() throws ObjectStreamException;
07-23
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值