帮我分析下列java代码:abstract class GirlFriend { abstract void speak (); abstract void cooking (); } Class ChinaGirlFriend extends GirlFriend { void speak (){ System . out . println ("你好"); } void cobking (){ System . out . println ("水煮鱼"); } } class AmericanGirlFriend extends GirlFriend { void speak (){ System . out . println (" hello "); } void cooking (){ System . out . println (" roast beff”); } } class Boy { GirlFriend friend ; void setGirlfriend ( GirlFriend f ){ friend = f ; } void showGirlFriend (){ friend . speak (); friend . cooking (); } } public class Example5_12{ public static void main ( String args []){ GirlFriend girl = newChinaGirlFriend (); Boy boy = new Boy (); boy . setGirlfriend ( girl ); boy . showGirlFriend (); girl = new AmericanGirlFriend (); boy . setGirlfriend ( girl ); boy . showGirlFriend (); } }
时间: 2024-04-22 07:28:59 浏览: 103
学习的java代码
这段代码定义了一个抽象类GirlFriend,包含了两个抽象方法speak()和cooking()。然后又定义了两个类ChinaGirlFriend和AmericanGirlFriend,分别继承了GirlFriend类,并实现了speak()和cooking()方法。接着定义了一个Boy类,包含了一个GirlFriend类型的属性friend,以及setGirlfriend()和showGirlFriend()方法。最后在主函数中创建了一个ChinaGirlFriend对象girl,并将其作为参数传递给Boy对象的setGirlfriend()方法,然后调用showGirlFriend()方法输出girl的speak()和cooking()方法。接着又创建了一个AmericanGirlFriend对象girl,并将其作为参数传递给Boy对象的setGirlfriend()方法,再次调用showGirlFriend()方法输出girl的speak()和cooking()方法。整个程序演示了面向对象中的继承和多态的概念。
阅读全文