1. 说出下面程序的执行结果:
interface InterfaceA {
String S = "good ";
void f();
}
abstract class ClassA {
abstract void g();
}
class ClassB extends ClassA implements InterfaceA {
void g() {
System.out.print(S);
}
public void f() {
System.out.print(" "+ S);
}
}
public class Test {
public static void main(String[] args) {
ClassA a = new ClassB();
InterfaceA b = new ClassB();
a.g();
b.f();
}
}
答案:good good
2.编程题:
利用接口做参数,写个计算器,能完成加减乘除运算。
(1)定义一个接口Compute含有一个方法int computer(int n, int m)。
(2)设计四个类分别实现此接口,完成加减乘除运算。
(3)设计一个类UseCompute,类中含有方法:public void useCom(Compute com, int one, int two),此方法能够用传递过来的对象调用computer方法完成运算,并输出运算的结果。
(4)设计一个主类Test,调用UseCompute中的方法useCom来完成加减乘除运算。
public class Test{
public static void main(String[] args){
UseCompute a = new UseCompute();
Add s1 = new Add();
Sub s2 = new Sub();
Mul s3 = new Mul();
Div s4 = new Div();
System.out.print("和:");a.useCom(s1,4,2);
System.out.print("差:");a.useCom(s2,4,2);
System.out.print("积:");a.useCom(s3,4,2);
System.out.print("商:");a.useCom(s4,4,2);
}
}
interface Compute{
int compute(int n,int m);
}
class Add implements Compute{
public int compute(int n,int m){
return n+m;}
}
class Sub implements Compute{
public int compute(int n,int m){
return n-m;
}
}
class Mul implements Compute{
public int compute(int n,int m){
return n*m;}
}
class Div implements Compute{
public int compute(int n,int m){
return n/m;}
}
class UseCompute{
public void useCom(Compute com, int one, int two){
System.out.println(com.compute(one,two));
}
}
3.按如下要求编写Java程序:
(1)定义接口A,里面包含值为3.14的常量PI和抽象方法double area()。
(2)定义接口B,里面包含抽象方法void setColor(String c)。
(3)定义接口C,该接口继承了接口A和B,里面包含抽象方法void volume()。
(4)定义圆柱体类Cylinder实现接口C,该类中包含三个成员变量:底圆半径radius、
圆柱体的高height、颜色color。
(5)创建主类来测试类Cylinder。
interface A{
float PI = 3.14f;
double area();
}
interface B{
void setColor(String c);
}
interface C extends A, B{
void volume();
}
class Cylinder implements C{
private int radius;
private int height;
private String color;
public Cylinder(){}
public Cylinder(int radius, int height, String color){
this.radius = radius;
this.height = height;
this.color = color;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getColor() {
return color;
}
public double area() {
return radius*2*PI*height + radius*radius*PI;
}
public void setColor(String c) {
}
public void volume() {
float volumeCount = radius*radius*PI;
System.out.println("体积为:" + volumeCount);
}
}
public class Test{
public static void main(String[] args) {
Cylinder c = new Cylinder(6, 5, "white");
System.out.println("表面积为:" + c.area());
c.volume();
}
}