贷款购买房屋时,支付首付款是一种功能操作,定义在Payment接口中。住宅产权房屋类和商业产权房屋类均具有支付首付款的功能。依据以上内容,创建一个接口和两个类:
(1)接口Payment,包含:
- double downPay(double price,double area):一个计算房屋首付款的方法,参数price代表房屋每平方米的价格,area代表房屋的总平方数,即面积。
package gy1; public interface Payment { double downPay(double price,double area); }
(2) Payment接口的非抽象使用类——Residence类(住宅产权房屋类),包含:
- double downPay(double price,double area):重写计算房屋首付款的方法,并将结果返回(住宅产权房屋的首付比例为总房款的20%)。
package gy1; public class Residence implements Payment { double price; double area; public void Residence(double price,double area) { this.price=price; this.area=area; } public double downPay(double price,double area) { return price*area*0.20; } }
(3) Payment接口的非抽象使用类——Commercial类(商业产权房屋类),包含:
- double downPay(double price,double area):重写计算房屋首付款的方法,并将结果返回(商业产权房屋的首付比例为总房款的45%)。
package gy1; public class Commercial implements Payment{ double price; double area; public Commercial(double price,double area) { this.price=price; this.area=area; } public double downPay(double price,double area) { return price*area*0.45; } }
在主类Test中,创建住宅产权房屋对象,完成住宅产权房屋首付款的计算。再将定义商业产权房屋对象传递给Payment接口对象,之后利用接口回调完成商业产权房屋首付款的计算。输入测试数据,完成结果的输出。
package gy1; import java.util.*; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); Residence resi = new Residence(); System.out.println("价格"); double price=in.nextDouble(); System.out.println("面积"); double area=in.nextDouble(); System.out.println("住宅产权房屋的首付是:"+resi.downPay(price, area)); Payment pay = new Commercial(price, area); System.out.println("商业产权房屋的首付是:"+pay.downPay(price, area)); } }
(4)运行结果