当前位置:首页 > 期末复习题
}
public double findArea() {
return 2*(3/4)*bian*bian +3*bian*length; } }
11.定义一个类,描述一个家庭,其中包括私有的钱数(属性)、受保护的祖传秘方(方法,
在其中写输出语句模拟即可)、只在家族中能够使用的运输工具(方法,在其中写输出语句进行模拟),公共的门牌号码(属性)。将这个家庭放置在一个包中(一个大院),编写一个该家庭的子类,放置在另一个包中。测试其中几种被可见性修饰符修饰过的属性和方法。 程序一:
package yard;
public class Family{ private double money; void useCar(){ System.out.println(\ } protected void peiFang(){ System.out.println(\ } public int familyNum; } 程序二:
package dalian;
import yard.Family; public class TestVisible{ public static void main(String[] args){ Family f=new Family();
System.out.println(\门牌号码是:\ //System.out.println(\钱数\ //f.useCar(); //f.peiFang();
SunFamily sf=new SunFamily(); //sf.peiFang(); sf.usePeiFang(); } }
class SunFamily extends Family{ public void usePeiFang(){ this.peiFang(); }
25
public void usePlane(){ System.out.println(\ } }
12.定义一个接口CanFly,描述会飞的方法public void fly();
分别定义类飞机和鸟,实现CanFly接口。
定义一个测试类,测试飞机和鸟,在main方法中创建飞机对象和鸟对象,再定义一个makeFly()方法,其中让会飞的事物飞。并在main方法中调用该方法,让飞机和鸟起飞。 class InterfaceSample
{
public static void main(String arg[]) { Plane p1=new Plane(); Bird b1=new Bird(); Dog d1=new Dog(); makeFly(p1); makeFly(b1);
if (d1 instanceof CanFly)//作用四:用instanceof判断是否实现了接口,即是否能飞 { System.out.println(\ makeFly((CanFly)d1); }
CanFly f1=new Plane(); CanFly f2=new Bird(); makeFly(f1); makeFly(f2); }
static void makeFly(CanFly f) {f.fly();} }
interface CanFly { void fly();}
class Plane implements CanFly { public void fly()
{ System.out.println(\ } }
class Bird implements CanFly { public void fly()
{System.out.println(\ }
class Dog{ void run(){System.out.println(\
26
}
13. 利用接口继承完成对生物、动物、人三个接口的定义,其中生物接口定义呼吸抽象方法,动物接口定义了吃饭和睡觉两个抽象方法,人接口定义了思维和学习两个抽象方法;定一个普通人 类实现上述三个接口定义的抽象方法。 interface Biology {
void breath(); }
interface Animal extends Biology {
void ate();
void sleep(); }
interface Man extends Animal {
void think(); void study(); }
class NormalMan implements Man,Animal,Biology {
private String name;
NormalMan(String name) { this.name=name;} public String getName() { return name;} public void breath()
{ System.out.println(name+\ public void ate()
{ System.out.println(name+\ public void sleep()
{ System.out.println(name+\ public void think()
{ System.out.println(name+\ public void study()
{ System.out.println(name+\ }
public class InterfaceExtend {
public static void main(String[] args) {
NormalMan zhangsan=new NormalMan(\ zhangsan.breath(); zhangsan.ate();
27
zhangsan.sleep(); zhangsan.think(); zhangsan.study(); } }
14 接口Volume如下,试编制类TriVolume实现该接口,并计算三棱柱的体积(底面为等边三角形)。 接口为:
Public interface Volume {
public double findVolume(double bian, double length); }
类为: class Trival { double bian; Trival() { bian=1.0; } Trival(double b) { bian=b; } double findArea() {
return (3/4)*bian*bian;
} }
答案:
class TriVolume extends Trival implements Volume {
double bian,length;
TriVolume(double b, double l) {
super(b); length=l; }
public double findArea() {
28
共分享92篇相关文档