Think in Java(四):复用类

1. 每一个非基本类型的对象都有一个toString方法,而且当编译器需要一个String而你却只有一个对象时,该方法便会被调用。
public class SprinklerSystem {
	private String valve;

	public String toString() {
		value = "test";
		return "valve = " + valve;
	}

	public static void main(String[] args) {
		SprinklerSystem sprinklers = new SprinklerSystem();
		System.out.println(sprinklers);
	}
} 
/* Output:
value = "test";
*///:~

2. Java会自动在子类的构造器中插入对父类构造器的调用,即会先调用父类的构造器,如果父类没有无参的构造器,那就要通过super(param)显式调用父类带参构造器

class Art {
	Art() {
		print("Art constructor");
	}
}

class Drawing extends Art {
	Drawing() {
		print("Drawing constructor");
	}
}

public class Cartoon extends Drawing {
	public Cartoon() {
		print("Cartoon constructor");
	}

	public static void main(String[] args) {
		Cartoon x = new Cartoon();
	}
} 
/* Output:
Art constructor
Drawing constructor
Cartoon constructor
*///:~

3. 不能认为一个变量是final的,就认为无法改变它的值,final的意思是无法将引用只想另一个新的对象。
public class FinalArguments {
	void with(final Gizmo g) {
		//! g = new Gizmo(); // Illegal -- g is final
	}
}

4. 继承及初始化:
访问Beetle.main()方法时,加载器开始启动并找到Beetle类的编译代码,在对它进行加载的过程中,编译器注意到它有一个父类。
于是开始加载父类,然后父类中的static初始化即会被执行...

class Insect {
	private int i = 9;
	protected int j;

	Insect() {
		print("i = " + i + ", j = " + j);
		j = 39;
	}

	private static int x1 = printInit("static Insect.x1 initialized");

	static int printInit(String s) {
		print(s);
		return 47;
	}
}

public class Beetle extends Insect {
	private int k = printInit("Beetle.k initialized");

	public Beetle() {
		print("k = " + k);
		print("j = " + j);
	}

	private static int x2 = printInit("static Beetle.x2 initialized");

	public static void main(String[] args) {
		print("Beetle constructor");
		Beetle b = new Beetle();
	}
} 
/* Output:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*///:~


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。