java高级玩法
内部类通过外部类来实例化 :
package com.yuanyu.Demo08;
public class Outer { //外部类
private int id;
public void out(){
System.out.println("Outer");
}
class Inner{ //内部类
public void in(){
System.out.println("Inner");
}
}
}
package com.yuanyu.Demo08;
public class Application {
public static void main(String[] args) {
Outer outer = new Outer();
//通过外部类来实例内部类
Outer.Inner inner = outer.new Inner();
inner.in(); //Inner
}
}
内部类可以获取外部类的私有属性和方法 :
package com.yuanyu.Demo08;
public class Outer { //外部类
private int id=10;
public void out(){
System.out.println("Outer");
}
class Inner{ //内部类
public void in(){
System.out.println("Inner");
}
public void getId(){
System.out.println(id);
}
}
}
package com.yuanyu.Demo08;
public class Application {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
//内部类可以获取外部类的私有属性
inner.getId(); //10
}
}
一个java类中只能有public class类,但是可以有多个class类
局部内部类(定义在方法中的类):
package com.yuanyu.Demo08;
public class Outer { //外部类
public void out(){
class Inner{
//局部内部类
public void in(){
}
}
}
}
匿名对象的使用:
package com.yuanyu.Demo08;
public class Test {
public static void main(String[] args) {
new Apple().eat(); //没有名字初始化类,不用将实例保存到变量中
}
}
class Apple{
public void eat(){
System.out.println("eat apples");
}
}
用类来实现接口:
package com.yuanyu.Demo08;
public class Test {
public static void main(String[] args) {
UserService userService = new UserService() { //实现接口的类(匿名类)
@Override
public void hello() {
}
};
}
}
interface UserService{
void hello();
}