---
title: "Inner class与匿名类相关问题汇总"
author: "danlley"
date: "2007-09-12T17:03:45Z"
tags: ["C", "C#", "C++"]
slug: "inner-class"
draft: false
lastmod: "2007-09-12T17:03:45Z"
id: 123346
url: "https://danlley.iteye.com/blog/123346"
---

1)如果存在3个类，一个是普通类A其中有个方法a()，接口B有个方法a()，这时，当类C既继承A又实现B的时候，会出现方法混乱现象。这样的情况在编译器中是不允许存在的。

2)内部类中无法定义static静态块。

3)匿名类对于接口的实现才有存在的实际价值，但是对于普通类，如果通过匿名类对其进行继承，顶多只是对现有类的复写，由于在向上转型的过程中会对实现类的接口按照父类的方法进行窄化处理，因此，即便匿名类对父类进行了功能的扩充，但事实上这些扩充的方法根本是没有机会使用到的。如果出现需要在匿名类对父类进行扩充的情况，可视情况将其定义成新独立类或者内部类。并且应该考虑类的命名以及方法的命名是否存在问题。

4)Inner class可以被protected、private、static甚至final进行修饰，但是，如果一个Inner class被修饰为一个final类型时，那么他就无法再进行派生子类

以下代码仅供参考：

java 代码

01. package interfaceandinnerclass;
02. public class FriendFatherImpl implements FriendFather, FriendFatherOther {
03. public void test() {
04. }
05. protected static class A {
06. void a() {
07. System.out.println("A is called");
08. }
09. void x() {
10. System.out.println("XX is called");
11. }
12. }
13. private class B extends A {
14. public B(){}
15. void b() {
16. System.out.println("A is called");
17. }
18. }
19. private interface C {
20. void c();
21. }
22. private interface D {
23. void d();
24. void x();
25. }
26. //  public abstract class S extends B implements C,D{
27. //  }
28. public static C mytest() {
29. System.out.println("FriendFatherImpl is called");
30. return new C() {
31. public void c() {
32. System.out.println("C is called");
33. }
34. };
35. }
36. public static B myTest(){
37. FriendFatherImpl friendFatherImpl=new FriendFatherImpl();
38. return friendFatherImpl.new B(){
39. public void first(){System.out.println("first is called");}
40. public void second(){System.out.println("second is called");}
41. public void thrid(){System.out.println("thrid is called");}
42. public void fourth(){System.out.println("fourth is called");}
43. };
44. }
45. public static void main(String\[] args) {
46. C c = mytest();
47. c.c();
48. B b=myTest();
49. b.a();
50. b.b();
51. b.x();
52. }
53. }

 

注：请注意其中绿色注释部分：

java 代码

1. //  public abstract class S extends B implements C,D{
2. //  }

这段代码事实上是无法编译通过的，之所以放在这里，主要是为了说明第一点问题。

 

**备注：**此文档在9月将一直处于维护状态。