文章目录
- 一、题1
- 1.1 问题描述
- 1.2 代码块
- 1.3 运行截图
- 二、题2
- 2.1 问题描述
- 2.2 代码块
- 2.3 运行截图
一、题1
1.1 问题描述
(1)创建一个用于数学运算接口,算数运算加、减、乘和除都继承该接口并实现具体的算数运算。(2)编写一个测试类进行运行测试。
1.2 代码块
package mypackage;
import java.util.Scanner;
public interface IComputer {
int computer(int one,int two);
class Add implements IComputer{
public int computer(int one, int two) {
return one+two;
}
}
class Sub implements IComputer{
public int computer(int one, int two) {
return one-two;
}
}
class Mul implements IComputer{
public int computer(int one, int two) {
return one*two;
}
}
class Div implements IComputer{
public int computer(int one, int two) {
if(two==0){
System.out.println("Divide by zero, meaningless");
System.exit(0);
}
return one/two; //若类型为short、int、long,除数为0会报错
}
}
class UseComputer{
public static void useCom(IComputer com,int one,int two){
System.out.println(com.computer(one,two));
}
}
}
package mypackage;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
IComputer.UseComputer.useCom(new IComputer.Add(),a,b);
IComputer.UseComputer.useCom(new IComputer.Sub(),a,b);
IComputer.UseComputer.useCom(new IComputer.Mul(),a,b);
IComputer.UseComputer.useCom(new IComputer.Div(),a,b);
}
}
1.3 运行截图
二、题2
2.1 问题描述
(1)定义一个水果抽象类,该类中提供一个水果种植抽象方法,苹果、草莓都继承水果抽象类,并实现该抽象方法。(2)编写测试类进行运行测试。
2.2 代码块
package CumtJava;
abstract class Fruit
{
abstract double getweight();
}
class Apple extends Fruit //苹果
{
double w;
String s;
Apple(double w,String s)
{
this.w=w;
this.s=s;
}
public double getweight()
{
return w;
}
}
class Peach extends Fruit //桃子
{
double w;
String s;
Peach(double w,String s)
{
this.w=w;
this.s=s;
}
public double getweight()
{
return w;
}
}
class Orange extends Fruit //橘子
{
double w;
String s;
Orange(double w,String s)
{
this.w=w;
this.s=s;
}
public double getweight()
{
return w;
}
}
package CumtJava;
public class Test {
public static void main(String[] args) {
Fruit[] f=new Fruit[3];
f[0]=new Apple(100,"苹果");
f[1]=new Peach(200,"桃子");
f[2]=new Orange(300,"橘子");
System.out.println("水果的类型和重量如下:");
for(int i=0;i<3;i++)
{
System.out.println(f[i].getweight());
System.out.println(f[i].getClass().getName());
}
}
}