封装与继承

【实验十一】

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","蓝");
	}
}
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值