版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
《Java语言程序设计》第二套题答案第二套题一、简答题1什么是多态性?方法的重载和覆盖有何区别?阅读下列代码,指出其中存在的重载和覆盖,写出输出结果是什么?解释为什么这样输出?(15分)classClass1{ publicvoidfind(){ System.out.println("Class1.find"); }}classClass2extendsClass1{ publicvoidfind(){ System.out.println("Class2.find"); }}classClass3{ publicvoidget(Class1one){ System.out.println("get(Class1)"); one.find(); } publicvoidget(Class2two){ System.out.println("get(Class2)"); two.find(); }}publicclassTest1{ publicstaticvoidmain(String[]args) { Class1one=newClass2(); Class3three=newClass3(); three.get(one); }}get(Class1)Class2.find多态:就是父类引用可以持有子类对象。这时候只能调用父类中的方法,而子类中特有方法是无法访问的,因为这个时候(编译时)你把他看作父类对象的原因,但是到了运行的时候,编译器就会发现这个父类引用中原来是一个子类的对像,所以如果父类和子类中有相同的方法时,调用的会是子类中的方法,而不是父类的。
方法重载是让类以统一的方式处理不同类型数据的一种手段。多个同名函数同时存在,具有不同的参数个数/类型。覆盖方法的签名完全相同,但函数体不同Class2继承Class1其中Class2对Class1find方法进行了覆盖Class3中对get方法进行了重载输出如上结果是因为多态,调用的是Class1的find方法。2、请说说final、finally的区别和作用,举例说明用法;另外用自己的语言介绍throw/throws有什么联系和区别?在程序中应如何使用?(15分)final是全局变量声明的时候使用,意思是这个变量不可被修改,不可被override,一般用于声明常量,或者系统设置的值。finally是在try-catch-finally块中配套使用,作用是,不管代码执行了try还是catch,最后一定会执行finally里面的代码如:方法finalvoidf(){System.out.println("dddd");}属性finalintaa;try{
}catch(Exceptione){
}finally{//一定会执行的代码
}3、编写一个描述老师基本情况的类,属性包括姓名,教工号,基本工资,岗位工资和绩效工资,方法包括信息输出,设置姓名和教工号,设置三种工资金额,计算总工资(三种工资加起来)和税后工资(按如下方式计算,3000以内不收税,3000-5000之间的部分扣10%,大于5000的部分扣15%)。在main方法中对方法进行测试(15分)publicclassTestTeacher{staticclassT{privateStringxingming;privateStringjiaogonghao;privatefloatjibengongzhi;privatefloatgangweigongzhi;privatefloatjixiao;publicStringgetXingming(){returnxingming;}publicvoidsetXingming(Stringxingming){this.xingming=xingming;}publicStringgetJiaogonghao(){returnjiaogonghao;}publicvoidsetJiaogonghao(Stringjiaogonghao){this.jiaogonghao=jiaogonghao;}publicfloatgetJibengongzhi(){returnjibengongzhi;}publicvoidsetJibengongzhi(floatjibengongzhi){this.jibengongzhi=jibengongzhi;}publicfloatgetGangweigongzhi(){returngangweigongzhi;}publicvoidsetGangweigongzhi(floatgangweigongzhi){this.gangweigongzhi=gangweigongzhi;}publicfloatgetJixiao(){returnjixiao;}publicvoidsetJixiao(floatjixiao){this.jixiao=jixiao;}publicfloatzhonggongzhi(){returnjibengongzhi+gangweigongzhi+jixiao;}publicfloatshuihougongzhi(){floatzhonggongzhi;zhonggongzhi=zhonggongzhi();if(zhonggongzhi<3000){returnzhonggongzhi;}elseif(zhonggongzhi>=3000&&zhonggongzhi<5000){returnzhonggongzhi-(zhonggongzhi-3000)*0.1f;}elseif(zhonggongzhi>=5000){returnzhonggongzhi-(zhonggongzhi-3000)*0.15f;}return-1;}}publicstaticvoidmain(String[]args){Tteacher=newT();teacher.setXingming("klo");teacher.setJiaogonghao("1230000");teacher.setJibengongzhi(1000);teacher.setGangweigongzhi(1000);teacher.setJixiao(1000);System.out.println("zhonggongzhi:"+teacher.zhonggongzhi());System.out.println("shuihougongzhi:"+teacher.shuihougongzhi());}}4、Java中实现多线程有几种方式?这几种方式有什么区别?然后采取其中一种方式设计一个线程例子,在例子中构造4个线程对象实现对同一数据类对象进行操作(数据初始值为10),其中线程对象1对数据执行乘以10的操作,线程对象2对数据执行乘以20的操作,对象3对数据执行+30的操作,线程对象4对数据执行+40的操作,要求考虑线程同步,保证每一步数据操作的正确性。要求提供程序代码以及运行结果截图(15分)答:常用的方式有1、继承Thread类实现方法run()不可以抛异常无返回值2、实现Runnable接口实现Runnable接口实现方法run()不可以抛异常无返回值3、线程池线程由线程池提交,管理importstaticjava.lang.Thread.sleep;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.logging.Level;importjava.util.logging.Logger;publicclassTestExecutor{intnumber=10;publicstaticvoidmain(String[]ss){finalTestExecutortestExecutor=newTestExecutor();testExecutor.test();}publicvoidtest(){ExecutorServicecachedThreadPool=Executors.newCachedThreadPool();cachedThreadPool.execute(newRunnableImpl());cachedThreadPool.execute(newRunnableImpl1());cachedThreadPool.execute(newRunnableImpl2());cachedThreadPool.execute(newRunnableImpl3());}publicvoidxiugai(intthreadType){synchronized(this){switch(threadType){case0:number=number*10;break;case1:number=number*20;break;case2:number=number+30;break;case3:number=number+40;break;default:break;}System.out.println(Thread.currentThread().getName()+":"+number);}}privateclassRunnableImplimplementsRunnable{publicRunnableImpl(){}@Overridepublicvoidrun(){try{while(true){xiugai(0);sleep(3000);}}catch(InterruptedExceptionex){Logger.getLogger(TestExecutor.class.getName()).log(Level.SEVERE,null,ex);}}}privateclassRunnableImpl1implementsRunnable{publicRunnableImpl1(){}@Overridepublicvoidrun(){try{while(true){xiugai(1);sleep(3000);}}catch(InterruptedExceptionex){Logger.getLogger(TestExecutor.class.getName()).log(Level.SEVERE,null,ex);}}}privateclassRunnableImpl2implementsRunnable{publicRunnableImpl2(){}@Overridepublicvoidrun(){try{while(true){xiugai(2);sleep(3000);}}catch(InterruptedExceptionex){Logger.getLogger(TestExecutor.class.getName()).log(Level.SEVERE,null,ex);}}}privateclassRunnableImpl3implementsRunnable{publicRunnableImpl3(){}@Overridepublicvoidrun(){try{while(true){xiugai(3);sleep(3000);}}catch(InterruptedExceptionex){Logger.getLogger(TestExecutor.class.getName()).log(Level.SEVERE,null,ex);}}}}二、编程题1、编写一个图形用户界面程序,包含两个按钮,一个信息标签(label)和一个显示面板,两个按钮分别为“掷色子”和“移动”,在显示面板中显示一个小汽车(用小圆\矩形以及线绘制),随机设定小汽车的初始位置,当点击“掷色子”按钮,随机产生移动信息(上移,下移,左移,右移,移动几步),并显示在信息标签中,点击移动,按照产生的移动信息,让小汽车进行移动。要求提供完整程序代码以及运行结果截图(20分)importjava.awt.Graphics;importjava.util.Random;publicclassmainextendsjavax.swing.JFrame{intx=100;inty=50;intrandomNum=0;intrandomPosition=0;String[]strs={"上移","下移","左移","右移"};publicmain(){initComponents();}@SuppressWarnings("unchecked")//<editor-folddefaultstate="collapsed"desc="GeneratedCode">privatevoidinitComponents(){jButton1=newjavax.swing.JButton();jButton2=newjavax.swing.JButton();jLabel1=newjavax.swing.JLabel();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);getContentPane().setLayout(newjava.awt.GridBagLayout());jButton1.setText("掷色子");jButton1.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jButton1ActionPerformed(evt);}});getContentPane().add(jButton1,newjava.awt.GridBagConstraints());jButton2.setText("移动");jButton2.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jButton2ActionPerformed(evt);}});getContentPane().add(jButton2,newjava.awt.GridBagConstraints());getContentPane().add(jLabel1,newjava.awt.GridBagConstraints());pack();}//</editor-fold>privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){Randomrandom=newRandom();randomNum=random.nextInt(4)+1;randomPosition=random.nextInt(4);jLabel1.setText(strs[randomPosition]+randomNum+"步");}privatevoidjButton2ActionPerformed(java.awt.event.ActionEventevt){repaint();}publicstaticvoidmain(Stringargs[]){try{for(javax.swing.UIManager.LookAndFeelInfoinfo:javax.swing.UIManager.getInstalledLookAndFeels()){if("Nimbus".equals(info.getName())){javax.swing.UIManager.setLookAndFeel(info.getClassName());break;}}}catch(ClassNotFoundException|InstantiationException|IllegalAccessException|javax.swing.UnsupportedLookAndFeelExceptionex){java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}//</editor-fold>//</editor-fold>/*Createanddisplaytheform*/java.awt.EventQueue.invokeLater(newRunnableImpl());}@Overridepublicvoidpaint(Graphicsg){super.paint(g);switch(randomPosition){case0:y=y-randomNum*15;break;case1:y=y+randomNum*15;break;case2:x=x-randomNum*15;break;case3:x=x+randomNum*15;break;default:break;}g.drawRect(x,y,40,40);}//Variablesdeclaration-donotmodifyprivatejavax.swing.JButtonjButton1;privatejavax.swing.JButtonjButton2;privatejavax.swing.JLabeljLabel1;//EndofvariablesdeclarationprivatestaticclassRunnableImplimplementsRunnable{publicRunnableImpl(){}@Overridepublicvoidrun(){newmain().setVisible(true);}}}2、编写一个班级推优(三好生)投票管理程序。列出参与推优的学生名单(8名),可以勾选进行投票,要求每个参选学生前面有图标表示候选人的性别,每人可以投4名候选人,每次投票后能够显示当前投票人数以及每名候选者得票数,图形化柱状图显示得票数,可以保存投票结果到文本文件。要求提供完整程序代码以及运行结果截图(20分)/**Tochangethislicenseheader,chooseLicenseHeadersinProjectProperties.*Tochangethistemplatefile,chooseTools|Templates*andopenthetemplateintheeditor.*/packagetestjava;importjava.awt.BorderLayout;importjava.awt.Font;importjava.util.List;importjavax.swing.JCheckBox;importorg.jfree.chart.ChartFactory;importorg.jfree.chart.ChartPanel;importorg.jfree.chart.JFreeChart;importorg.jfree.chart.axis.CategoryAxis;importorg.jfree.chart.axis.NumberAxis;importorg.jfree.chart.axis.ValueAxis;importorg.jfree.chart.plot.CategoryPlot;importorg.jfree.chart.plot.PlotOrientation;importorg.jfree.data.category.CategoryDataset;importorg.jfree.data.category.DefaultCategoryDataset;/****@authorldl*/publicclassTestFr1extendsjavax.swing.JFrame{privatejavax.swing.JButtonjButton1;privatejavax.swing.JCheckBoxjCheckBox1;privatejavax.swing.JCheckBoxjCheckBox2;privatejavax.swing.JCheckBoxjCheckBox3;privatejavax.swing.JCheckBoxjCheckBox4;privatejavax.swing.JCheckBoxjCheckBox5;privatejavax.swing.JCheckBoxjCheckBox6;privatejavax.swing.JPaneljPanel1;/***CreatesnewformTestFr*/publicTestFr1(){initComponents();CategoryDatasetdataset=getDataSet();JFreeChartchart=ChartFactory.createBarChart("统计",//图表标题"投票统计",//目录轴的显示标签"数量",//数值轴的显示标签dataset,//数据集PlotOrientation.VERTICAL,//图表方向:水平、垂直true,false,false);CategoryPlotplot=chart.getCategoryPlot();//获取图表区域对象NumberAxisnumberaxis=(NumberAxis)plot.getRangeAxis();numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());CategoryAxisdomainAxis=plot.getDomainAxis();//水平底部列表domainAxis.setLabelFont(newFont("黑体",Font.BOLD,14));//水平底部标题domainAxis.setTickLabelFont(newFont("宋体",Font.BOLD,12));//垂直标题ValueAxisrangeAxis=plot.getRangeAxis();//获取柱状rangeAxis.setLabelFont(newFont("黑体",Font.BOLD,15));chart.getLegend().setItemFont(newFont("黑体",Font.BOLD,15));chart.getTitle().setFont(newFont("宋体",Font.BOLD,20));//设置标题字体ChartPanelchartPanel=newChartPanel(chart,true);jPanel1.setLayout(newBorderLayout(0,0));jPanel1.add(chartPanel);jPanel1.repaint();}/***Thismethodiscalledfromwithintheconstructortoinitializetheform.*WARNING:DoNOTmodifythiscode.Thecontentofthismethodisalways*regeneratedbytheFormEditor.*/@SuppressWarnings("unchecked")//<editor-folddefaultstate="collapsed"desc="GeneratedCode">//GEN-BEGIN:initComponentsprivatevoidinitComponents(){jCheckBox1=newjavax.swing.JCheckBox();jPanel1=newjavax.swing.JPanel();jCheckBox5=newjavax.swing.JCheckBox();jCheckBox2=newjavax.swing.JCheckBox();jCheckBox3=newjavax.swing.JCheckBox();jCheckBox6=newjavax.swing.JCheckBox();jCheckBox4=newjavax.swing.JCheckBox();jButton1=newjavax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jCheckBox1.setText("班长");jCheckBox1.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox1ActionPerformed(evt);}});javax.swing.GroupLayoutjPanel1Layout=newjavax.swing.GroupLayout(jPanel1);jPanel1.setLayout(jPanel1Layout);jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,411,Short.MAX_VALUE));jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,0,Short.MAX_VALUE));jCheckBox5.setText("大山4");jCheckBox5.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox5ActionPerformed(evt);}});jCheckBox2.setText("卫生1");jCheckBox2.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox2ActionPerformed(evt);}});jCheckBox3.setText("大山2");jCheckBox3.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox3ActionPerformed(evt);}});jCheckBox6.setText("大山5");jCheckBox6.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox6ActionPerformed(evt);}});jCheckBox4.setText("大山3");jCheckBox4.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jCheckBox4ActionPerformed(evt);}});jButton1.setText("投票");javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jCheckBox1).addComponent(jCheckBox2).addComponent(jCheckBox3).addComponent(jCheckBox4).addComponent(jCheckBox5).addComponent(jCheckBox6).addComponent(jButton1)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(14,14,14).addComponent(jCheckBox1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jCheckBox2).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(jCheckBox3).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jCheckBox4).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jCheckBox5).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jCheckBox6).addGap(18,18,18).addComponent(jButton1).addContainerGap(83,Short.MAX_VALUE)).addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE));pack();}//</editor-fold>//GEN-END:initComponents/***@paramargsthecommandlinearguments*/publicstaticvoidmain(Stringargs[]){/*SettheNimbuslookandfeel*///<editor-folddefaultstate="collapsed"desc="Lookandfeelsettingcode(optional)">/*IfNimbus(introducedinJavaSE6)isnotavailable,staywiththedefaultlookandfeel.*Fordetailssee/javase/tutorial/uiswing/lookandfeel/plaf.html*/try{for(javax.swing.UIManager.LookAndFeelInfoinfo:javax.swing.UIManager.getInstalledLookAndFeels()){if("Nimbus".equals(info.getName())){javax.swing.UIManager.setLookAndFeel(info.getClassName());break;}}}catch(ClassNotFoundExceptionex){java.util.logging.Logger.getLogger(TestFr.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(InstantiationExceptionex){java.util.logging.Logger.getLogger(TestFr.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(IllegalAccessExceptionex){java.util.logging.Logger.getLogger(TestFr.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(javax.swing.UnsupportedLookAndFeelExceptionex){java.util.logging.Logger.getLogger(TestFr.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}//</editor-fold>/*Createanddisplaytheform*/java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newTestFr().setVisible(true);}});} privatevoidjCheckBox1ActionPerformed(java.awt.event.ActionEventevt){JCheckBoxjCheckBox=(JCheckBox)evt.getSource();intintValue=dataset.getValue(0,0).intValue();if(jCheckBox.isSelected()){intValue++;}else{intValue--;}dataset.setValue(intValue,"1","1");}privatevoidjCheckBox5ActionPerformed(java.awt.event.ActionEventevt){//TODOaddyourhandlingcodehere:JCheckBoxjCheckBox=(JCheckBox)evt.getSource();intintValue=dataset.getValue(4,4).intValue();if(jCheckBox.isSelected()){intValue++;}else{intValue--;}dataset.setValue(intValue,"4","4");}privatevoidjCheckBox2ActionPerformed(java.awt.event.ActionEventevt){
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年实战手册吊带安全培训内容记录
- 机械社团工作总结报告2026年答题模板
- 2026年答题模板公司春运安全培训内容
- 2026年家政培训师授权合同
- 2026年老人孩子安全培训内容系统方法
- 合肥市长丰县2025-2026学年第二学期六年级语文第五单元测试卷部编版含答案
- 2026年租房合同简介协议书避坑指南
- 2026年货运代理服务合同条款
- 运城市垣曲县2025-2026学年第二学期五年级语文第五单元测试卷(部编版含答案)
- 四平市铁东区2025-2026学年第二学期六年级语文第五单元测试卷部编版含答案
- 蔬果采购员管理制度
- 2026年广州市高三语文一模作文题目解析及范文:那些被遗忘的后半句
- 广东省广州市黄埔区第八十六中学2024-2025学年八年级下学期4月期中物理试题(含答案)
- 2026年及未来5年市场数据辽宁省环保行业市场行情动态分析及发展前景趋势预测报告
- 2026年广东食品药品职业学院单招职业技能测试题库附参考答案详解(a卷)
- 企业价值成长中耐心资本的驱动作用研究
- 兰铁局防护员考核制度
- 2026届安徽省江南十校高三上学期10月联考数学试题(解析版)
- 2025年河南工业职业技术学院单招职业适应性考试题库带答案解析
- DZ/T 0275.4-2015岩矿鉴定技术规范第4部分:岩石薄片鉴定
- 贵州省六盘水市英武水库工程环评报告
评论
0/150
提交评论