2012-08-24 15 views
2

Java中的所有接口(如Serializable, Cloneable, Observable等)都帶有後綴「-able」。但是,java.lang.Throwable不是接口,而是類。JDK中的命名約定:java.lang.Throwable

我瞭解java.lang.Throwable的用法,但我無法理解爲什麼它以這種方式命名。這種異常是否有特定的原因?

+2

我不認爲這有什麼用類一直接口與否,而是描述他們做什麼。這個類是「可序列化的」,類是「可破解的」,類是「可觀察的」,類是「可丟棄的」(並且已經被扔掉了) – MadProgrammer

回答

3

採訪lost to the dustbins of the internet解釋了爲什麼在作出決定作出的Throwable類而不是一個接口。主要的原因是因爲拋出異常需要跟蹤狀態

JDC: Why is Throwable not an interface? The name kind of suggests it should have been. 
Being able to catch for types, that is, something like try{}catch (<some interface or 
class>), instead of only classes. That would make [the] Java [programming language] 
much more flexible. 

JG: The reason that the Throwable and the rest of those guys are not interfaces is 
because we decided, or I decided fairly early on. I decided that I wanted to have some 
state associated with every exception that gets thrown. And you can't do that with 
interfaces; you can only do that with classes. The state that's there is basically 
standard. There's a message, there's a snapshot, stuff like that — that's always there.  
and also, if you make Throwable an interface the temptation is to assign, to make any 
old object be a Throwable thing. It feels stylistically that throwing general objects 
is probably a bad idea, that the things you want to throw really ought to be things 
that are intended to be exceptions that really capture the nature of the exception and 
what went on. They're not just general data structures. 
0

Throwable類是Java語言中所有錯誤和異常的超類。只有作爲此類(或其某個子類)的實例的對象由Java虛擬機拋出,或者可以由Java throw語句拋出。同樣,只有這個類或它的一個子類可以是catch子句中的參數類型。

它包含了所有可以拋出,在許多方式的接口/抽象類做的事情。我想這應該是具有-able後綴的邏輯。儘管這不是一個爭論點,但總的來說,你不應該假設任何以able結尾的東西都是一個接口。

更新
從現實生活中的另一個例子,是在我的項目之一......我不得不做出一個(抽象)的超類,其子類可以被緩存(Memcached中)。它抽象了添加,刪除,更新緩存所需的所有邏輯。這會是一個好名字嗎?我把它命名爲Cacheable。這個想法是,如果它是Cacheable它將被緩存。

所以,它只是語義 - 與命名模式無關。唯一的命名模式Java已經在這裏給出的是:詹姆斯·高斯林,太陽的前副總裁和Java的主要設計師Java Naming Convention