《Thinking In Java第四版》拾遗 转自我的github --http://katsurakkkk.github.io/2016/05/Thinking-In-Java%E7%AC%AC%E5%9B%9B%E7%89%88-%E6%8B%BE%E9%81%97 近日 ...
《Thinking In Java第四版》拾遗
转自我的github --http://katsurakkkk.github.io/2016/05/Thinking-In-Java%E7%AC%AC%E5%9B%9B%E7%89%88-%E6%8B%BE%E9%81%97
近日重读了《Thinking In Java第四版》(可能版本比较老),发现一些有趣的和值得注意的地方,在此作个记录。
不能用返回值对函数进行overload,因为有可能调用方并不关心返回值,这就造成了二义性。如:
1 void f();2 int f();
可以用this引用在构造函数中调用过载的构造函数,但是只能调用一个,并且构造函数调用必须是我们做的第一件事,否则编译器会报错。另外,只能在构造函数中调用其它构造函数。
1 public class ThisTest { 2 public ThisTest() { 3 // System.out.print("Constructor"); 4 this(1); 5 // this(1, 2); 6 } 7 public ThisTest(int n) {} 8 9 public ThisTest(int n, int m) {}10 }
接口中定义的字段会自动具有static和final属性。它们不能是‘空白final’,但可以初始化成非常数表达式。如下:
1 public interface RandVals {2 int rint = (int)(Math.random() * 10);3 long rlong = (long)(Math.random() * 10);4 float rfloat = (float)(Math.random() * 10);5 double rdouble = (double)(Math.random() * 10);6 }
内部类看起来没有什么特别的地方,然而当我们准备upcast到一个基类的时候,内部类就开始发挥其关键作用。这是由于内部类随后可以完全进入不可见或者不可用的状态--对任何人都如此。所以我们可以非常方便的隐藏实施细节。我们得到的全部回报就是一个基础类或者接口的句柄,而且甚至有可能不知道准确的类型。如下:
1 abstract class Contents { 2 abstract public int value(); 3 } 4 5 interface Destination { 6 String readLabel(); 7 } 8 9 class Parcel {10 private class PContents extends Contents {11 private int i = 11;12 13 @Override14 public int value() {15 return i;16 }17 }18 19 protected class PDestination implements Destination {20 private String label;21 22 private PDestination(String whereTo) {23 label = whereTo;24 }25 26 @Override27 public String readLabel() {28 return label;29 }30 }31 32 public Destination dest(String s) {33 return new PDestination(s);34 }35 36 public Contents cont() {37 return new PContents();38 }39 }40 41 class Test {42 public static void main(String[] args) {43 Parcel p = new Parcel();44 Contents c = p.cont();45 Destination d = p.dest("ShenZhen");46 // Illegal -- can't access private class:47 //! Parcel.PContents c = p.new Pcontents();48 }49 }
看下面这段代码
1 public class InnerClass { 2 public Contents count() { 3 return new Contents() { 4 private int i = 11; 5 public int value() { 6 return i; 7 } 8 } 9 }10 }
1. 为对象分配的存储空间初始化成二进制零。
若调用了break和continue语句,finally语句也会得以执行。与break和continue一道,finally排除来了Java对跳转语句的需求。关于异常的准则(用异常做下列事情):
自定义序列化:
clone()方法是定义在Object类中的,但是可能考虑到不是每个类都需要克隆的能力,所以把Object中的clone方法设置成了protected。如果某个类想要拥有clone的特性,可以在类中对clone进行覆写,将它设置成public,然后再里面调用super.clone()。
线程的堵塞可能是由于下述五方面的原因造成的:
wait()和notify()比较特别的地方是这个方法属于基础类Object的一部分,不像sleep(),suspend()以及resume()那样属于Thread的一部分。而且,我们能调用wait()的唯一地方是在一个同步的方法或者代码块内部。若在一个不同步的地方调用了wait()或者notifiy(),尽管程序仍然会通过编译,但是在运行的时候会得到一个IllegalMonitorStateException。
原标题:《Thinking In Java第四版》拾遗
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。