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 interface Compute
{
public int computer(int n,int m) ;
}
//加法类
class Jia implements Compute
{
public int computer(int n, int m)
{
return n+m;
}
}
//减法类
class Jian implements Compute
{
public int computer(int n, int m)
{
return n-m;
}
}
//乘法类
class Cheng implements Compute
{
@Override
public int computer(int n, int m)
{
return n*m;
}
}
//除法类
class Chu implements Compute
{
public int computer(int n, int m)
{
if(m==0)
{
System.out.println("被除数不能为0");
}
return n/m;
}
}
//新建类实现调用
class UseCompute
{
public void useCom(Compute com, int one, int two)
{
System.out.println(com.computer(one,two) );
}
}
public class Test {
public static void main(String[] args)
{
UseCompute a = new UseCompute( ) ;
System.out.print("2+3=");
a.useCom(new Jia(), 2, 3);
System.out.print("2-3=");
a.useCom(new Jian(), 2, 3);
System.out.print("2*3=");
a.useCom(new Cheng(), 2, 3);
System.out.print("3/2=");
a.useCom(new Chu(), 3, 2);
System.out.print("2/3=");
a.useCom(new Chu(), 2, 3);
System.out.println("除法取整运算");
System.out.print("3/0=");
a.useCom(new Chu(), 6, 0);
}
}
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。
public class TestIo{
public static void main(String[] args) {
TestIo.Cylinder v = new TestIo().new Cylinder();
System.out.println("area = "+v.area());
System.out.println("volume = "+v.volume());
}
interface A{
double PI = 3.14;
abstract double area();
}
interface B{
abstract void setColor(String c);
}
interface C extends A,B{
abstract double volume();
}
public class Cylinder implements C{
public double radius = 2.0;
public double height = 4.0;
public String color = "red";
public double area(){
return ((this.radius)*(this.radius)*(this.PI));
}
public void setColor(String c){
System.out.println("red");
}
public double volume(){
return ((this.radius)*(this.radius)*(this.PI)*(this.height));
}
}
}