2013-02-28 73 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