码迷,mamicode.com
首页 > 编程语言 > 详细

Think in Java(四):复用类

时间:2015-01-23 16:22:52      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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
*///:~


Think in Java(四):复用类

标签:

原文地址:http://blog.csdn.net/zdp072/article/details/43056625

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!