2013-02-28 107 views
3

正如我最近開始編程,我有點卡在這個編碼領域。Java嵌套類問題

有一個名爲嵌套類的編程課。但是,當我想要使用它時,它實際上不會做作業所需。這裏是什麼,我需要實現一個例子:

public class Zoo { 
    ... 
    public static class monkey { 
     ... 
    } 
} 

,並在主

Zoo zoo1 = new Zoo(); 
... 
zoo1.monkey.setage(int); 
... 

但這裏有一個問題,每當我想打電話從zoo1猴子,調試器說,這是。不可能的(請記住,我想這樣做,而無需創建猴子的實例)

在此先感謝

更新:我只是想知道,如果它是一個有點語言LIMI那麼oracle自己可以如何輕鬆地使用system.out.printf?

回答

1

monkey看起來靜給我。不過,它們應該是public而不是Public

我會說setage()不是一個靜態方法。如果是這樣的話,如果年齡是一隻猴子的財產,那麼靜態地稱之爲毫無意義 - 你的年齡會被設定?

但問題在於,您似乎無法通過外部類類型的變量訪問靜態內部類。所以它應該是Zoo.monkey而不是zoo1.monkey

如果您只是想控制範圍或命名,您可以使用packages

例如,你可以有以下幾點:

package com.example.application.feature; 

public class MyClass { 
    public void f() { 
     System.out.println("Hello"); 
    } 
} 
在源文件中

稱爲com/example/application/feature/MyClass.java

+0

感謝您的貢獻,但實際的問題是調試器說猴類本身不被識別。所以我不能只寫:zoo1.monkey。我仍然可以編寫Zoo.monkey。 – lkn2993 2013-02-28 10:52:24

+1

我的錢就是因爲這是語言的故意限制(爲什麼當內部類無法訪問實例字段時,通過外部類的特定實例訪問靜態內部類?),但我可能是錯的。調試器準確地說了些什麼? – Vlad 2013-02-28 10:54:36

+0

它表示該對象或字段不存在。 – lkn2993 2013-02-28 11:01:01

1

編輯:我沒有看到你注意「(請記住,我想這樣做,而無需創建猴子的實例)」前問

有時,搜索可能會幫助你從節省一些time.Direct Quotion這個地址:http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Inner Classes

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

class OuterClass { ... class InnerClass { ... } }

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. The next figure illustrates this idea.

An Instance of InnerClass Exists Within an Instance of OuterClass

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also called anonymous inner classes). Both of these will be discussed briefly in the next section.

+0

因此system.out.printf應該創建爲一個實例嗎? – lkn2993 2013-02-28 10:58:13

2

您無法通過Zoo實例訪問猴類,但實際上並沒有任何意義。如果你想訪問主要的猴子的靜態方法,你可以使用下面的例子

public class Zoo { 

    public static void main(String[] args) { 
     // Example 1 
     monkey.setage(3); 
     // Example 2 
     Zoo.monkey.setage(3); 
    } 

    public static class monkey { 
     private static int age; 

     public static void setage(int age) { 
      monkey.age = age; 
     } 
    } 
} 

但是你究竟在努力完成什麼?

+0

如果你將猴子的年齡設置在實例外,那麼它如何被引用到實例本身?那麼我想要做的是應該訪問和調用zoo1實例(這是唯一的)的猴子的方法(如果可能的話)。再次感謝:) – lkn2993 2013-02-28 10:54:45

+0

如果你不想創建一個猴子的實例,那麼沒有屬於zoo1實例的猴子。 – 2013-02-28 15:50:14