【实验十一】
1.分析程序的结果,并上机验证。
class Sa{99
int x,y;
public void setXy(int x,int y) {
this.x=x;
this.y=y;
}
public int result() {
return x+y; }
}
class Sb extends Sa{
int x;
public int result(){
super.x=5;
x=super.result()/x;
return x;
} }
class Sc {
public static void main(String aa[]){ Sa s=new Sa();
s.setXy(5,10);
System.out.println(“sa result:”+s.result());
Sb s2=new Sb();
s2.x=3;
s2.y=10;
System.out.println(“sb result:”+s2.result());
}}
sa result:15 sb result:5
2.阅读程序,分析程序的输出结果。
A()
B()
A:f()
B:f()
3.定义一个矩形类,它包含两个数据成员:长和宽,以及包含用于求面积的成员方法。再定义矩形类的子类—长方体类,增加一个数据成员高以及用来求长方体体积的成员方法。在主方法中用其求长方形的面积和长方体的体积。
class Sju {
int x,y,s;
public void setS(int x,int y) {
this.x = x;
this.y = y;
}
public int getS() {
return x*y;
}
public int getx() {
return x;
}
public int gety() {
return y;
}
}
class Vti extends Sju{
int h;
public int seth;
public int geth() {
return h;
}
public void seth(int h) {
this.h=h;
}
public int ti() {
return this.getS()*this.geth(); }
}
public class main {
public static void main(String args[]) {
Sju s = new Sju();
s.setS(3,4);
System.out.println("矩形的面积是"+s.getS());
Vti v = new Vti();
v.setS(3, 4);
v.seth(5);
System.out.println("体积"+v.ti());
}
}
4.借用继承,根据下面的类图优化电子宠物系统。
class pet {
String name;
int energy=60;//能量值
int love=60;//亲密度
String say;
public String getname() {
return name;
}
public int getenergy() {
return energy;
}
public int getlove() {
return love;
}
pet(String name) {
this.name = name;
System.out.println("名字是:"+this.name+",亲密度是:"+this.love+",能量值是:"
+this.energy);
}
}
class dog extends pet{
String strain;//品种
public dog(String name,String strain) {
super(name);
this.strain=strain;
System.out.println(this.say()+"\n"+"品种是:"+this.strain);
}
public String say() {
String say="汪汪汪.....";
return say;
}
}
class penguin extends pet {
String sex;
public penguin(String name,String sex) {
super(name);
this.sex=sex;
System.out.println(this.say()+"\n"+"性别是:"+this.sex);
}
public String say() {
String say="叽叽叽.....";
return say;
}
}
class cat extends pet{
String eye;
public cat(String name,String eye) {
super(name);
this.eye=eye;
System.out.println(this.say()+"\n"+"眼睛是:"+this.eye+"色");
}
public String say() {
String say="喵喵喵....";
return say;
}
}
public class ceshi {
public static void main(String args[]) {
dog d = new dog("小黑","柯基");
penguin p = new penguin("大鹅","雌性");
cat c = new cat("小m","蓝");
}
}