java課后習(xí)題答案(2)
public double h(double x){ return Math.sqrt(x); } }
class A3 implements A{
public void f(int x){
System.out.println("你好:"+x); }
public void g(int x,int y){
double z=(double)x/y; System.out.println(z); }
public double h(double x){ return 1/x; } }
public class ZuoYe5_3{
public static void main(String args[ ]){
A a=new A1();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A2();
a.f(10);
a.g(12,20);
System.out.println(a.h(100));
a=new A3();
a.f(10);
a.g(12,20);
System.out.println(a.h(100)); } }
利用面向接口編程的方法,編寫計(jì)算錐形體積的完整程序,注意錐形的底可以為圓形,矩形,或梯形等。(對(duì)細(xì)節(jié)滿足開閉原則。)
4求下列程序運(yùn)行結(jié)果:
class A{
public double y=11.456789;
public void f(){
y=y+1;
System.out.printf("y是double型的變量,y=%f\n",y); } }
class B extends A{
int y=0;
public void g(){
y=y+100;
System.out.printf("y是int型的變量,y=%d\n",y); } }
class Example5_3{
public static void main(String args[ ]){
B b=new B();
b.y=200;
b.g(); //調(diào)用子類新增的方法
b.f(); //調(diào)用子類繼承的方法 } }
5.求下列程序運(yùn)行結(jié)果
class A{
int m=0,n=0;
long f(){
return m+n; } }
class B extends A{
int m=1,n=1;
long f(){
long result=0;
super.m=10;
super.n=20;
result=super.f()+(m+n);
return result; }
long g(){
long result=0;
result=super.f();
return result/2; } }
public class Example5_7{
public static void main(String args[ ]){
B b=new B();
b.m=3;
b.n=7;
long resultOne=b.g();
long resultTwo=b.f();
long resultThree=b.g();
System.out.println("resultOne="+resultOne); System.out.println("resultTwo="+resultTwo); System.out.println("resultThree="+resultThree); } }
(6) 即所謂的開閉原則,對(duì)_________關(guān)閉,對(duì)______________開放。
答: 修改,擴(kuò)展
(7)編寫一個(gè)面向抽象的完整程序,求柱形體積,計(jì)算方法底*高,但底面積的算法經(jīng)常要變化。于是對(duì)于求底面積可以設(shè)一個(gè)抽象類Geometry 。柱形面對(duì)具有抽象類的Geometry設(shè)計(jì)。最后完成對(duì)圓形底面積的柱形,和梯形底面積的柱形計(jì)算體積。
(8)求下列程序的運(yùn)行結(jié)果。
interface Show{
void show(); }
class A implements Show{
public void show(){
System.out.println("I love This Game"); } }
class B implements Show{
public void show(){
System.out.println("我喜歡看NBA");} }
class C{
public void f(Show s){ //接口作為參數(shù)
s.show(); } }
public class Example5_13{
public static void main(String args[]){
C c=new C();
c.f(new A());
c.f(new B());} }
答: I love This Game
我喜歡看NBA
(9)寫出下面程序的運(yùn)行結(jié)果:
public class Example5_18{
public static void main(String args[ ]){
int n=0,m=0,t=0;
try{
t=9999;
m=Integer.parseInt("8888");
n=Integer.parseInt("12s3a"); //發(fā)生異常,轉(zhuǎn)向catch
System.out.println("我沒有機(jī)會(huì)輸出"); }
catch(Exception e){
System.out.println("發(fā)生異常");
n=123; }
System.out.println("n="+n+",m="+m+",t="+t); }}
答:發(fā)生異常 n=123, m=8888, t=9999
