class Outter
{
void function()
{
class Inner
{
void show()
{
System.out.println("hahaha");
}
}
new Inner().show();
}
}
class localinner
{
public static void main(String[] args)
{
new Outter().function();
}
}各位大大,如果不在function()中new一个 Inner 类的对象,也就是不写new Inner().show();在主函数怎么样写会访问到Inner 类的show()方法,才能打印“hahaha”.
{
void function()
{
class Inner
{
void show()
{
System.out.println("hahaha");
}
}
new Inner().show();
}
}
class localinner
{
public static void main(String[] args)
{
new Outter().function();
}
}各位大大,如果不在function()中new一个 Inner 类的对象,也就是不写new Inner().show();在主函数怎么样写会访问到Inner 类的show()方法,才能打印“hahaha”.
public void fun();
}
class C{
public void fun2(){
this.print ( new A() {
public void fun(){
System.out.println("Inner---->Hello");
}
}
);
}
public void print(A a){
a.fun();
}
}
public class OODemo20{
public static void main(String []args){
new C().fun2();
}
}
运行结果:Inner---->Hello匿名内部类很简单的举例..... 看看吧....
Terminology: Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. 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.http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html所有嵌套类(Nested class)分为两类:静态与非静态。非静态嵌套类(Non-static nested classes)又被称为内部类。而内部类(Inner class)含两特别品种,本地类(Local class)和匿名类(Anonymous class),楼主问题中提及的就是Local class
虽然是官方的,但这命名法我觉得仍有点歧义,可以认同嵌套类的说法,但static nested class就不是Inner的了?所以我想更正式的名称更应该是Non-static nested classes吧。这也是为什么中文更多见的用内部类称呼也包含了静态嵌套类了吧,含义上与英文无法同步了。
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.
local class的scope是local,所以在方法外不可见,这个三楼说过了。
这里有总结:A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private.http://docs.oracle.com/javase/tutorial/java/javaOO/summarynested.html但我觉得红色字体部分的说法还是不严谨,在静态上下文中声明的inner class还是不是必须需要instance of its enclosing class呢?比如以下情况:class Outter {
static void function() {
class Inner {
void show() {
System.out.println("hahaha");
}
}
new Inner().show();
}
}这种情况怎么解释呢?希望能找到不是不严谨的说法。However, not all inner classes have enclosing instances; inner classes in static contexts, like an anonymous class used in a static initializer block, do not.