(1)内部类的同名方法
内部类可以调用外层类的方法,如果内部类有同名方法必须使用"OuterClass.this.MethodName()"格式调用(其中OuterClass与MethodName换成实际外部类名及其方法;this为关键字,表示对外部类的引用);若内部类无同名方法可以直接调用类的方法。匿名内部类
但类无法直接调用内部类的private方法,外部类同样无法直接调用其它类的private方法。注意:内部类直接使用外部类的方法与该方法的权限与是否static无关,它取决于内部类是否有同名方法。
package innerclass;
public class OuterClass {
private void outerMethod() {
System.out.println("It's Method of OuterClass");
}
public static void main(String[] args) {
OuterClass t = new OuterClass();
OuterClass.Innerclass in = t.new Innerclass();
in.innerMethod();
}
class Innerclass {
public void innerMethod() {
OuterClass.this.outerMethod();// 内部类成员方法与外部类成员方法同名时,使用this调用外部类的方法
outerMethod();// 内部类没有同名方法时执行外部类的方法
}
private void outerMethod() {
System.out.println("It's Method of Innerclass");
}
}
}
输出结果为:
It's Method of OuterClass It's Method of Innerclass
(2)内部类的实例化
内部类实例化不同于普通类,普通类可以在任意需要的时候实例化,而内部类必须在外层类实例化以后方可实例化,并与外部类建立关系
因此在外部类中的非static方法中,是可以实例化内部类对象
private void outerMethod() {
System.out.println("It's Method of OuterClass");
Innerclass in = new Innerclass();//在外部类的outerMethod方法中实例化内部类是可以啊
}但在static方法中,就要注意啦!!!!不能在static方法中直接new内部类,否则出现错误:
No enclosing instance of type OuterClass is accessible. Must qualify the allocation with an enclosing instance of type OuterClass (e.g. x.new A() where x is an instance of OuterClass).
这是因为静态方法是在类实例化之前就可以使用的,通过类名调用,这时动态内部类都还没实例化呢,怎么用,总不能调用一个不存在的东西吧。
如果想在Static方法中new内部类,可以把内部类声明为Static
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-23912-1.html
存e租宝是14600
我是比较含蓄的那一波
好漂亮