package quickanswer.chapter8
class Creature {
val range: Int = 10
val env: Array[Int] = new Array[Int](this.range)///calls the range() 方法而不是对字段的的直接引用 和java 的区别
}
class Ant extends Creature {
override val range = 2
}
object ConstructionOrder extends App {
val ant= new Ant
println(ant.range);
println(ant.env.length);
}
package quickanswer.chapter8;
class CreatureJava {
int range=10;
int[] env = new int[range];
public int getRange() {
return range;
}
}
class AntJava extends CreatureJava {
int range = 2;
@Override
public int getRange() {
return range ;
}
}
public class ConstructionOrderJava {
public static void main(String[] args) {
AntJava a=new AntJava();
System.out.println(a.range);
System.out.println(a.env.length);
}
}
public class Creature
{
public int range()
{
return this.range;
}
private final int range = 10;
public int[] env()
{
return this.env;
}
private final int[] env = new int[range()];
}
1. The Ant constructor calls the Creature constructor before doing its own construction.
2. The Creature constructor sets its range field to 10.
3. The Creature constructor, in order to initialize the env array, calls the range() getter.
4. That method is overridden to yield the (as yet uninitialized) range field of the Ant class.
5. The range method returns 0. (That is the initial value of all integer fields when an object is allocated.)
6. env is set to an array of length 0.
7. The Ant constructor continues, setting its range field to 2.
本文探讨Scala与Java在构造顺序及变量访问方面的差异。通过对比Scala和Java代码的执行结果,揭示Scala构造过程中对成员变量访问的独特机制,并提供反编译后的代码解释。
1137

被折叠的 条评论
为什么被折叠?



