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