java静态类和非静态类_关于java:静态和非静态内部类的区别?
我正在閱讀有效的Java 2 -項目22,它在標題中寫道:
"Favor static member classes over non-static"
但是在這一章的結尾
Implementations of the collection interfaces, such as Set and List,
typically use nonstatic member classes to implement their iterators:
// Typical use of a nonstatic member class
public class MySet extends AbstractSet {
... // Bulk of the class omitted
public Iterator iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator {
...
}
}
我做了一個測試程序,看看它們之間是否有任何區別,這里就是。
public class JavaApplication7 {
public static void main(String[] args) {
// TODO code application logic here
JavaApplication7 t = new JavaApplication7();
Inner nonStaticObject = t.getAClass();
Sinner staticObject = new JavaApplication7.Sinner();
nonStaticObject.testIt();
staticObject.testIt();
}
public Inner getAClass(){
return new Inner();
}
static class Sinner{
public void testIt(){
System.out.println("I am inner");
}
}
class Inner{
public void testIt(){
System.out.println("I am inner");
}
}
}
輸出是
I am inner
I am inner
所以,他們做了同樣的工作。
我想知道為什么在這個例子中使用非靜態類?
迭代器通常需要首先引用用于創建它的集合。可以使用一個顯式提供了對集合的引用的靜態嵌套類來實現這一點,也可以只使用一個隱式引用的內部類。
基本上,如果嵌套類的每個實例都需要一個封閉類的實例來操作(而該實例不變),那么您也可以將其設置為一個內部類。否則,將其設置為靜態嵌套類。
區別在于,非靜態內部類對包含類具有隱式引用。
public class JavaApplication7 {
//You can access this attribute in non-static inner class
private String anyAttribute;
public Inner getAClass(){
return new Inner();
}
static class Sinner{
public void testIt(){
//Here, you cannot access JavaApplication7.this
}
}
class Inner{
public void testIt(){
//Here, you can access JavaApplication7.this
//You can also access *anyAttribute* or call non-static method getAClass()
}
}
}
static與非靜態嵌套類的區別在于,非靜態嵌套類隱式地與外部類的一個實例相關聯,它們可以稱為OuterClassName.this。此引用在實現迭代器時很有用,因為它們需要訪問與其相關的集合的成員。您可以通過使用static嵌套類來實現相同的事情,該類顯式地將引用傳遞給外部類。
In the case of creating instance, the instance of non s
static inner class is created with the reference of
object of outer class in which it is defined……this
means it have inclosing instance …….
But the instance of static inner class
is created with the reference of Outer class, not with
the reference of object of outer class…..this means it
have not inclosing instance…
For example……
class A
{
class B
{
// static int x; not allowed here…..
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A o=new A();
A.B obj1 =o.new B();//need of inclosing instance
A.C obj2 =new A.C();
// not need of reference of object of outer class….
}
}
沒有靜態內部類,它是靜態嵌套類。"非靜態[嵌套]類的每個實例都隱式地與其包含類的封閉實例關聯…可以在封閉實例上調用方法。"
靜態嵌套類無權訪問封閉實例。
參考文獻:這條索線
總結
以上是生活随笔為你收集整理的java静态类和非静态类_关于java:静态和非静态内部类的区别?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java注解定义时间格式_SpringB
- 下一篇: java空指针处理例子_被同事的空指针硬