一、题目要求:
贷款购买房屋时,支付首付款是一种功能操作,定义在Payment接口中。住宅产权房屋类和商业产权房屋类均具有支付首付款的功能。依据以上内容,创建一个接口和两个类:
(1)接口Payment,包含:
double downPay(double price,double area):一个计算房屋首付款的方法,参数price代表房屋每平方米的价格,area代表房屋的总平方数,即面积。
(2) Payment接口的非抽象使用类——Residence类(住宅产权房屋类),包含:
double downPay(double price,double area):重写计算房屋首付款的方法,并将结果返回(住宅产权房屋的首付比例为总房款的20%)。
(3) Payment接口的非抽象使用类——Commercial类(商业产权房屋类),包含:
double downPay(double price,double area):重写计算房屋首付款的方法,并将结果返回(商业产权房屋的首付比例为总房款的45%)。
在主类Test中,创建住宅产权房屋对象,完成住宅产权房屋首付款的计算。再将定义商业产权房屋对象传递给Payment接口对象,之后利用接口回调完成商业产权房屋首付款的计算。输入测试数据,完成结果的输出。
二、代码如下
Payment类
package cn.hhh; /** * double downPay * 一个计算房屋首付款的方法, * */ public interface Payment { double downPay(double price, double area); }
Residence类
package cn.hhh; /** * double downPay(double price,double area): * 重写计算房屋首付款的方法 * */ public class Residence implements Payment { public double downPay(double price, double area) { return area * price * 0.2; } }
Commercial类
package cn.hhh; /** * double downPay(double price,double area): * 重写计算房屋首付款的方法 * */ public class Commercial implements Payment { public double downPay(double price, double area) { return price * area * 0.45; } }
Test类
package cn.hhh; import java.util.Scanner; /** * 在主类Test中, * 创建住宅产权房屋对象 */ public class Test { public static void main(String[] args) { Residence residence = new Residence(); Scanner scanner = new Scanner(System.in); System.out.println("Please enter the price per square meter (unit: RMB/million).:"); double price = scanner.nextDouble(); System.out.println("Please enter the area (square meter) you want to purchase:"); double area = scanner.nextDouble(); System.out.println("Hello, you need to pay the down payment of your residential property right:" + residence.downPay(price, area) + "万元"); Payment commercial = new Commercial(); System.out.println("Hello, the down payment of your commercial property right should be:" + commercial.downPay(price, area) + "万元"); } }