Java中的宏变量

Python017

Java中的宏变量,第1张

java中 final 有修饰符的变量称为常量,名称一般用大写。s1==s2是因为“ja”和“va”都是常量,jvm会自动计算出结果,然后在常量池里查找,找到就把地址引用过去。用 final 修饰了str 后原理也是一样的了。

-- 直接量,在js中有这个概念,java中没听说过

直接量也称为字面量,是JavaScript中一种对象的表示(或者说创建)方式,它可以通过直接给变量赋上JavaScript中原生对象值的方式从而转换为一个相应的对象。

对象直接量提供了一种创建并初始化新对象的简单而直接的方式。

var circle={x:0, y:0, radius:2,speed:function(){alert('ok')}}

说白了==>Javascript里直接量即对象的json表示法

供参考By monical

-- 宏替换 c/cpp里面的概念,不明

-- 常量池,java里指的是jvm的常量池,下面是原文:

For each type it loads, a Java Virtual Machine must store a constant pool. A constant pool is an ordered set of constants used by the type, including literals (string, integer, and floating point constants) and symbolic references to types, fields, and methods. Entries in the constant pool are referenced by index, much like the elements of an array. Because it holds symbolic references to all types, fields, and methods used by a type, the constant pool plays a central role in the dynamic linking of Java programs.

大概是讲常量池保存了各个类型的引用,对java这种动态语言很重要.

--宏常量 c/cpp里面的概念,不明

-- 常量,所有编程语言都有,java的常量就是给定的量,死的.比如int i= 1i就是常量,不同的常量存储的区域不大一样.

分static变量,final变量,全局变量,局部变量等.

程序运行时机优先级是:类加载-->静态代码块运行-->静态变量初始化-->对应的构造函数运行--->

System.out.println(Price.INSTANCE.currentPrice):

Price.INSTANCE:调用了构造方法,即打印"执行了构造函数 initPrice:"+ initPrice,此时initPrice虽然也是静态的,但还没有被执行到,所以此时的值为0。如果把“static double initPrice = 20”放在“static Price INSTANCE = new Price(2.8)”前面结果就不一样了。

currentPrice = initPrice - discount:

Price.INSTANCE:static Price INSTANCE = new Price(2.8)创建了Price对象,传入的参数是2.8,所以currentPrice = 0 - 2.8,结果为 -2.8。

Price p = new Price(2.8):

静态成员是在构造方法之前就完成了初始化操作,所以可以用类名直接调用,没有被静态化的成员是不能被类名直接调用的,必须创建对象进行初始化操作。而这里new创建了Price对象,就完成了Price里面所有成员的初始化操作,各个成员就都有了初始值。创建对象的时候会调用构造法,这里构造方法就是public Price(double discount){},所以就执行了构造方法里面的currentPrice = initPrice - discount,即currentPrice=20-2.8=17.2。

至于static double initPrice = 20被final修饰了,final是在类加载的时候就被赋值了,运行时机优先级更高吧,并且final赋值后就不能被修改。所以结果为:

执行了构造函数 initPrice:20.0

17.2

执行了构造函数 initPrice:20.0

17.2