1.静态内部类
①有名静态内部类
static class Heart{
{
System.out.println("doing....");
}
}
②匿名静态内部类
class Father {
public void eat() {
System.out.println("筷子吃饭....");
}
}
/**
* 外部类
*/
public class OutClass {
/**
* 匿名内部类
*/
static Father son = new Father(){
@Override
public void eat() {
System.out.println("筷子吃饭....");
}
};
}
2.用法:
①在非静态方法创建非静态内部类的对象,先创建外部类对象,是隐式,用this。
public class Body {
class Heart{
{
System.out.println("doing....");
}
}
public void get2(){
Heart heart = new Body().new Heart(); //这种方式也可以
Heart heart1 =this. new Heart(); //this可以省略
heart1 = this.new Heart(); //把class heart当成是全局变量,在语句中使用全局变量+this
}
}
②在静态方法中创建非静态内部类的对象,必须“显示”外部类对象。
public class Body {
class Heart{
{
System.out.println("doing....");
}
}
public static void get1(){
Heart heart2 = new Body().new Heart(); //静态方法中不能使用this 所以只能创建对象,先外部再内部
}
}
③在非静态方法中创建静态内部类的对象,直接创建类的对象。
④在静态方法中创建静态内部类的对象,直接创建类的对象。
原因:静态的在类加载的时候处理,静态方法直接分配地址,可以被直接调用。但是非静态的不是,必须创建对象才行。
注意:
思考:静态成员变量可以"直接"在非静态方法或代码块中使用,为什么?
静态的在类加载的时候处理:静态变量直接赋值 静态方法直接分配地址 静态代码块直接执行;非静态的只能在创建对象时执行操作:变量赋值 方法分配地址 代码块执行。
总结:JVM对静态的操作比非静态的靠前。
3.
①如果为static内部类只能直接定义在外部类中。方法中不能再有方法,只能方法中调用方法。
②只有有名静态内部类中才允许有静态成员(静态属性、静态代码块和静态方法)。
4.Lambda表达式
①如果方法没有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->单行语句,如下例:
@FunctionalInterface
interface IMammal {
void move(String name);
}
public class Test {
public static void main(String[] args) {
IMammal whale = (name) -> {
System.out.println(name+"正在移动......");
};
whale.move("鲸鱼");
}
}
Lambda 表达式:
@FunctionalInterface
interface IMammal {
void move(String name);
}
public class Test {
public static void main(String[] args) {
IMammal whale = (name) -> System.out.println(name+"正在移动......");
whale.move("鲸鱼");
}
}
②如果方法有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->表达式,如下例:
@FunctionalInterface
interface IComputer {
int add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = (a, b) -> {
return a+b;
};
int result = computer.add(1,2);
System.out.println(result);
}
}
Lambda 表达式:
@FunctionalInterface
interface IComputer {
int add(int a, int b);
}
public class Test {
public static void main(String[] args) {
IComputer computer = (a, b) -> a+b;
int result = computer.add(1,2);
System.out.println(result);
}
}