Java 接口可以创建对象吗?匿名内部类怎么来的 ? Lambda表达式怎么来的?

很多小伙伴会疑问接口会不会创建对象,例如一下代码:

public interface Runnable {
     
 void run();
}

public static void main(String[] args) {
     

	Runnable r= new Runnable(){
     
	// some implementation
	}
	
}

乍一看,就好像Runnable接口创建了一个r对象,但实际上呢?

实际上,这是在创建一个类来实现Runnable接口

所以,当你写以下代码时:

Runnable runnable = new Runnable() {
     

        @Override
        public void run() {
     
            // TODO Auto-generated method stub

        }
    };

实际上你是创建了一个Runnable类实现了Runnable接口,而里面的 “run” 方法实际上是你重写的"Runnable"里的方法,而此种写法又叫“匿名内部类”,就是创建了一个只可以使用一次的类,我们大可以叫他“临时演员”。

匿名内部类怎么来的?

新事物的产生肯定是因为旧事物的不便捷才产生的,在没有匿名内部类的时候,我们的代码是这样的:

interface operation {
     
	int add(int x,int y);
}
class Myclass implements operation {
     
	@override
	int add(int x,int y) {
     
	return x + y;
	}
}
class Main {
     
public static void main(String[] args) {
     
	Myclass m = new Myclass();
	m.add(1,2);
} 
}
  • 由上面三部分我们可以知到,由一个operation 接口,“Myclass”类继承了operation 接口并且重写了里面的add()方法,而在实现的时候还必须在Main里创建对象调用。并且Myclass类只使用了一次,单独创建一个文件不免有点大材小用了.
  • 所以Java引出了匿名内部类的概念,来简便我们的代码:
interface operation {
     
	int add(int x,int y);
}
class Main {
     
public static void main(String[] args) {
     
	// 此处实际上运用了“基于接口的多态”
	opreation obj = new Myclass() {
     
		@override
		int add(int x,int y) {
     
		return x + y;
		}
	}
	// 我们创建了Myclass对象并implement接口operation,obj对象还重写了add()方法
} 
}

通过代码量相比我们可以发现使用匿名内部类更加简洁,特别是当我们的类只需要使用一次时(单个对象时),下面就来总结以下“匿名内部类的优缺点”

  • 优点:代码更加简洁(more concise)
  • 缺点:只适用于单个对象(only can be used to single object)

那么Lambda表达式又怎么来的呢?

Java在Java8以后推出了Lamda表达式,其中Lambda表达式的作用之一就是代替匿名内部类:
先说一下Lambda表达式的组成:
(参数) -> {表达式}

interface operation {
     
	int add(int x,int y);
}
// 此接口为函数式接口
// 接口中只有一个抽象方法的接口为函数式接口
class Main {
     
public static void main(String[] args) {
     
	// 此处运用了“基于接口的多态”
	opreation obj = (int x,int y) -> return x + y;
	// obj为接口operation的引用
	obj.operation(1,2);
	} 
}

此处直接将operation接口的重写用Lambda表达式代替了,代码更加简洁了
Lambda表达式主要有三个功能:
1、Enable to treat functionality as a method argument, or code as data.
2、A function that can be created without belonging to any class.
3、A lambda expression can be passed around as if it was an object and executed on demand.

你可能感兴趣的:(Java,lambda,java)