"除了靜態方法,還有靜態類。我們稍後會更詳細地討論這些。現在,讓我舉個例子:"

例子:
public class StaticClassExample
{
    private static int catCount = 0;

    public static void main(String[] args) throws Exception
    {
        Cat bella = new Cat("Bella");
        Cat tiger = new Cat("Tiger");

        System.out.println("Cat count " + catCount);
    }

     public static class Cat
    {
        private String name;

        public Cat(String name)
         {
            this.name = name;
            StaticClassExample.catCount++;
         }
     }

}
2
任務
Java Syntax,  等級 6課堂 7
上鎖
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

您可以根據需要創建任意數量的 Cat 對象。但是靜態變量不是這種情況。靜態變量只存在一個副本。”

”在類聲明中使用static修飾符的主要目的是為了控制CatStaticClassExample類之間的關係。其思想大致是這樣的:Cat類沒有鏈接到StaticClassExample對象,不能訪問實例(非- static) StaticClassExample 類的變量。”

“所以我可以在類中創建類?”

“是的,Java是允許的,不過現在先別想太多,等我再跟你解釋一些事情的時候,就清楚了。”

“我希望如此,Rishi。”