java匿名内部类继承-java 匿名类意义?
发布时间:2023-04-27 09:21 浏览次数:次 作者:佚名
java匿名内部类一般是没有变量指向的对象,只能使用一次
如下代码java匿名内部类继承,为了使用抽象类People的eat方法还要去继承然后复写eat方式java匿名内部类继承,非常麻烦。对于接口也是如此。
package com.lubby.nosynchronizedtest; public abstract class People { public abstract void eat() ; }package com.lubby.nosynchronizedtest; public class Teacher extends People { @Override public void eat() { System.out.println("老师正在吃饭"); } public static void main(String[] args) { People people = new Teacher(); people.eat(); } }在看如下代码,是不是很简单。之间new一个
package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { new People() { @Override public void eat() { System.out.println("我正在吃饭"); } }.eat(); } }仔细看看,发现是不是线程经常使用这种方法。线程的创建一般都是继承Threa抽象类或者Runable接口
package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { Thread thread1 = new Thread() { public void run() { System.out.println("线程1正在跑"); } }; thread1.start(); } }package com.lubby.nosynchronizedtest; public class Teacher { public static void main(String[] args) { Runnable runable = new Runnable() { @Override public void run() { System.out.println("run......."); } }; Thread thread = new Thread(runable); thread.start(); } }