Java枚举类的底层实现

这题来自于牛客网,后了解了枚举类的实现原理,理解了这题的真正意思。

 

枚举类在后台实现时,实际上是转化为一个继承了java.lang.Enum类的实体类,原先的枚举类型变成对应的实体类型,上例中AccountType变成了个class AccountType,并且会生成一个新的构造函数,若原来有构造函数,则在此基础上添加两个参数,生成新的构造函数,如上例子枚举类中:

枚举类的构造方法:

private AccountType(){ System.out.println(“It is a account type”); }

 

底层是:

class AccountType中,新的构造函数:

private AccountType(String s, int i){
        super(s,i);
     System.out.println(“It is a account type”);
 }

新添加若干字段来代表具体的枚举类型:

public static final AccountType SAVING;
public static final AccountType FIXED;
public static final AccountType CURRENT;

而且还会添加一段static代码段:

static{
    SAVING = new AccountType("SAVING", 0);
    FIXED = new AccountType("FIXED",0);
    CURRENT = new AccountType("CURRENT", 0);
   $VALUES = new AccountType[]{
         SAVING, FIXED, CURRENT
    } }

以此来初始化枚举中的每个具体类型。(并将所有具体类型放到一个$VALUE数组中,以便用序号访问具体类型) 

在初始化过程中new AccountType构造函数被调用了三次,所以Enum中定义的构造函数中的打印代码被执行了3遍。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: C is a general-purpose, high-level programming language that was first developed by Dennis Ritchie at Bell Labs in 1972. It is widely used for system programming, embedded systems, and application development. C has been influential in the development of many other programming languages, including C++, Java, and Python. Some of the key features of C include: - Low-level memory manipulation: C allows programmers to work directly with memory, which gives them a high degree of control over system resources. This can be useful for developing operating systems, device drivers, and other system-level software. - Structured programming: C supports structured programming constructs like loops, conditionals, and functions, which make it easier to write organized, readable code. - Portability: C is a portable language, which means that code written in C can be compiled and run on different hardware platforms and operating systems without modification. - Efficiency: C is a relatively low-level language, which means that it can be used to write code that runs quickly and uses few system resources. Overall, C is a powerful and versatile programming language that continues to be widely used in a variety of fields. ### 回答2: C是计算机领域中的一种高级编程语言。它由美国贝尔实验室的丹尼斯·里奇(Dennis Ritchie)于20世纪70年代初开发。C语言是一种强大而灵活的编程语言,被广泛用于开发各种应用程序、操作系统和嵌入式系统。 C语言被设计为一种通用的编程语言,它具有较低级语言的特点,如对内存的直接访问和对底层硬件的控制,同时又具备了高级语言的易用性和可移植性。 C语言的特点包括简洁、高效、灵活和可扩展性。它提供了丰富的语法和数据类型,使得开发者能够更自由地表达自己的想法和编写功能强大的程序。C语言也被广泛应用于算法和数据结构的教学,因为其简单的语法和强大的功能使得学习和实践变得更加容易。 C语言还具有良好的可移植性,可以在不同的平台上编写和运行。这使得C语言成为开发跨平台应用程序的理想选择。许多计算机操作系统、编译器和数据库等关键软件都是用C语言编写的。 总的来说,C语言作为一种高级编程语言,具有简洁、高效、灵活和可扩展的特点,被广泛应用于计算机科学与技术领域。无论是开发应用程序还是学习算法和数据结构,C语言都是一个重要的工具和基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值