首页 > 学院 > 开发设计 > 正文

构建器的初始化

2019-11-08 18:28:40
字体:
来源:转载
供稿:网友
class Tag {Tag(int marker) {System.out.PRintln("Tag(" + marker + ")");}}class Card {Tag t1 = new Tag(1); // Before constructorCard() {// Indicate we're in the constructor:System.out.println("Card()");t3 = new Tag(33); // Re-initialize t3}Tag t2 = new Tag(2); // After constructorvoid f() {System.out.println("f()");}Tag t3 = new Tag(3); // At end}public class OrderOfInitialization {public static void main(String[] args) {Card t = new Card();t.f(); // Shows that construction is done}}

初始化的顺序是由变量在类内的定义顺序决定的。即使变量定义大量遍布于方法定义的中间,那些变量仍会在调用任何方法之前得到初始化——甚至在构建器调用之前,就是先初始化成员变量,再构建器,最后是方法,所以上边的代码执行顺序是

Tag(1)Tag(2)Tag(3)Card()Tag(33)f()


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表