《Java编程思想》读书笔记(5)

本文探讨了Java中多态的概念及其实现方式,并通过具体代码示例展示了如何在不知道对象具体类型的情况下运行Applet或Swing组件,从而更好地体现了封装与多态的设计理念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天和vandalor讨论到多态的思想和好处,自己对多态也有了进一步的认识。再来想了想前面一篇笔记中的代码,想到如果用户能够在不知道到底是applet还是窗体的情况能够

跑起来的话,那应该更符合封装的思想了。所得代码如下:

<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>--> //Console.java
import
java.awt.*;
importjavax.swing.*;

publicclassConsole
{
publicstaticStringtitle(Objectobj)
{
Stringstr
="";
str
=obj.getClass().toString();
if(str.indexOf("class")!=-1)
{
str
=str.substring(6);
}
returnstr;
}
publicstaticvoidrun(JFrameframe,intwidth,intheight)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(frame));
frame.setSize(width,height);
frame.setVisible(
true);
}

publicstaticvoidrun(JAppletapplet,intwidth,intheight)
{
JFrameframe
=newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(applet));
frame.setSize(width,height);
frame.getContentPane().add(applet);
applet.init();
applet.start();
frame.setVisible(
true);
}

publicstaticvoidrun(JPanelpanel,intwidth,intheight)
{
JFrameframe
=newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle(title(panel));
frame.setSize(width,height);
frame.getContentPane().add(panel);
frame.setVisible(
true);

}

}
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->

//Test.java
import
javax.swing.*;

publicclassTestextendsJApplet
{

/**
*
@paramargs
*/
publicvoidinit()
{
JLabellb1
=newJLabel("Hello,World");
this.getContentPane().add(lb1);
}
publicstaticvoidmain(String[]args)
{
Testt1
=newTest();
Console.run(t1,
300,300);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值