6.9,匿名内部类怎么实现接口?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //测试类 public class Test { public static void main(String[] args) { //完成成员内部类内部测试 BallTest.Inner_m a= new BallTest(). new Inner_m(); System.out.println(a.play()); //完成方法内部类测试 BallTest a1= new BallTest(); System.out.println(a1.info()); //完成匿名内部类测试 Test test= new Test(); test.getRoad( new Test() { //题意说要在匿名内部类中实现接口,怎么做? }); } private void getRoad(Test test) { // TODO Auto-generated method stub } } //创建类BallTest public class BallTest implements Ball{ public String play() { // TODO Auto-generated method stub return null ; } // 创建成员内部类Inner_m public Inner_m getInner_m(){ return new Inner_m(); } class Inner_m implements Ball{ public String play() { // TODO Auto-generated method stub return "成员内部类" + '\n' + "打篮球" ; } } // 创建方法内部类 public String info(){ class Inner_f implements Ball{ public String play(){ return "********" + '\n' + "方法内部类" + '\n' + "打乒乓球" ; } } return new Inner_f().play(); } // 定义一个方法void playBall(Ball ball),调用play()方法 } public interface Ball { abstract String play(); } |
317
收起
正在回答
3回答
当接口定义为:
1 2 3 | public interface Ball { public void play(); } |
BallTest定义为:
1 2 3 4 5 | public class BallTest { public void playBall(Ball ball) { ball.play(); } } |
可以在main方法中:
1 2 3 4 5 6 | BallTest anony= new BallTest(); anony.playBall( new Ball(){ public void play(){ System.out.println( "匿名内部类:" ); } }); |
我是这么写的~~~
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧