Java 匿名內(nèi)部類詳解及實例代碼
Java 匿名內(nèi)部類詳解
匿名內(nèi)部類也就是沒有名字的內(nèi)部類
正因為沒有名字,所以匿名內(nèi)部類只能使用一次,它通常用來簡化代碼編寫
但使用匿名內(nèi)部類還有個前提條件:必須繼承一個父類或?qū)崿F(xiàn)一個接口
實例1:不使用匿名內(nèi)部類來實現(xiàn)抽象方法
abstract class Person {
public abstract void eat();
}
class Child extends Person {
public void eat() {
System.out.println("eat something");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Child();
p.eat();
}
}
運行結(jié)果:eat something
可以看到,我們用Child繼承了Person類,然后實現(xiàn)了Child的一個實例,將其向上轉(zhuǎn)型為Person類的引用
但是,如果此處的Child類只使用一次,那么將其編寫為獨立的一個類豈不是很麻煩?
這個時候就引入了匿名內(nèi)部類
實例2:匿名內(nèi)部類的基本實現(xiàn)
abstract class Person {
public abstract void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person() {
public void eat() {
System.out.println("eat something");
}
};
p.eat();
}
}
運行結(jié)果:eat something
可以看到,我們直接將抽象類Person中的方法在大括號中實現(xiàn)了
這樣便可以省略一個類的書寫
并且,匿名內(nèi)部類還能用于接口上
實例3:在接口上使用匿名內(nèi)部類
interface Person
{
public void eat();
}
public class Demo
{
public static void main(String[]
args) {
Person
p = new Person()
{
public void eat()
{
System.out.println("eat
something");
}
};
p.eat();
}
}
運行結(jié)果:eat something
由上面的例子可以看出,只要一個類是抽象的或是一個接口,那么其子類中的方法都可以使用匿名內(nèi)部類來實現(xiàn)
最常用的情況就是在多線程的實現(xiàn)上,因為要實現(xiàn)多線程必須繼承Thread類或是繼承Runnable接口
實例4:Thread類的匿名內(nèi)部類實現(xiàn)
public class Demo
{
public static void main(String[]
args) {
Thread
t = new Thread()
{
public void run()
{
for (int i
= 1;
i <= 5;
i++) {
System.out.print(i
+ "
");
}
}
};
t.start();
}
}
運行結(jié)果:1 2 3 4 5
實例5:Runnable接口的匿名內(nèi)部類實現(xiàn)
public class Demo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
}
};
Thread t = new Thread(r);
t.start();
}
}
運行結(jié)果:1 2 3 4 5
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
解決jasperreport導(dǎo)出的pdf每頁顯示的記錄太少問題
這篇文章主要介紹了解決jasperreport導(dǎo)出的pdf每頁顯示的記錄太少問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
springboot高并發(fā)下提高吞吐量的實現(xiàn)
這篇文章主要介紹了springboot高并發(fā)下提高吞吐量的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

