示例1:
package com.swust.面向对象; class Person1{
private String username="zhangsan";
public Person1(){
System.out.println("Person created......");
}
public String name ="";
class Student{
public Student(){
System.out.println("Student created......");
}
public String username="lisi";
public void show(){
System.out.println(this.getClass().getName());
System.out.println(username);
}
}
} class Person2{
private static String username = "lisi";
static class Student{
public void show(){
System.out.println(username);
}
}
} class Person3{
private static String useranme="wangwu";
static class Student{
public static void show(){
System.out.println(useranme);
}
}
} public class Example2{
public static void main(String[] args) {
// // person.show();
// //内部类为静态类
// Person2.Student person2 = new Person2.Student();
// person2.show();
// 由于内部类持有外部类的引用,因而可以访问外部类的成员变量 // Person3.Student.show();
了
Person1.Student person = new Person1().new Student();
person.show();
}
}
对于内部类的访问分为如下情况:
(1)普通情况下,访问内部类必须如下格式 : Person1.Student person = new Person1().new Student();
(2)内部类的方法为静态方法,Person3.Student person3 = new Person3.Student();
(3 局部内部类无法访问方法中的普通变量,将该变量设置为final,常量类型,由于方法调用结束的时候所要调用的参数就消失了,而对该参数添加final修饰符修饰后就变成常量,存储位置发生变化,存储在常量池中
示例2:
package com.swust.面向对象;
abstract class Base{
public abstract void show();
} class Student{
private static int age = 4;
public static void show(){
new Base(){
@Override
public void show() {
System.out.println("匿名内部类……"+age);
}
}.show();;
}
}
public class Example4 {
public static void main(String[] args) {
Student.show();
}
}
匿名内部类:内部类的简写形式,其实就是一个匿名子类对象,但是有前提,就是该内部类必须实现继承外部类或者实现一个接口
new Base(){
@Override
public void show() {
System.out.println("匿名内部类……"+age);
}
}
整条语句相当于创建一个匿名内部类的对象
示例3:
interface People{
void show1();
void show2();
} class Example{
public void show(){
new People(){
public void show1(){
System.out.println("show1 execute……");
}
public void show2(){
System.out.println("show2 execute……");
}
}.show1();
new People(){
public void show1(){
System.out.println("show1 execute……");
}
public void show2(){
System.out.println("show2 execute……");
}
}.show2();
}
} public class Example5 {
public static void main(String[] args) {
Example example = new Example();
example.show();
}
}
匿名内部类的使用场景:当函数参数是接口类型的时候,而且接口中的方法不超过三个,这时候可以利用匿名内部类作为实际参数进行传递
示例4:
package com.swust.面向对象; class Dog{
public void show(){
new Object(){
public void show(){
System.out.println("匿名内部类执行……");
}
}.show();;
} public void message(){
Object object = new Object(){
public void show(){
System.out.println("匿名内部类执行………………");
}
};
}
} public class Example6 {
public static void main(String[] args) {
new Dog().show();
}
}
在这里不能执行:object.show()语句,由于上面语句类似于将匿名内部类子类对象进行向上转型,转换为Object对象,而Object对象中没有show方法