编写程序,接收用户输入的信息,选择需要购买的房屋

目的:使用父类作为方法返回值来实现多态

运行效果:
在这里插入图片描述
父类:

package duotai;

public abstract class House {

	private String name;
	private double price;
	private String location;
	private double area;

	// 构造方法
	public House(String name, double price, String location, double area) {
		super();
		this.name = name;
		this.price = price;
		this.location = location;
		this.area = area;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public double getArea() {
		return area;
	}

	public void setArea(double area) {
		this.area = area;
	}

}

楼房子类:

package duotai;

public class LHouse extends House {
	private int floor;
	
	public LHouse(String name,double price,String location,double area,int floor){
		super(name,price,location,area);
		this.floor=floor;
	}
	@Override
	public String toString() {
		String str="名称:"+this.getName()+"\n价格:"+this.getPrice()+"\n位置:"
	+this.getLocation()+"\n面积:"+this.getArea()+"\n楼层:"+this.floor;
		return str;
	}

}

别墅子类:

package duotai;

public class HHouse extends House {
	private int garden;

	public HHouse(String name, double price, String location, double area,int garden) {
		super(name, price, location, area);
		this.garden=garden;
	}

	@Override
	public String toString() {
		String str="名称:"+this.getName()+"\n价格:"+this.getPrice()+"\n位置:"+this.getLocation()
				+"\n面积:"+this.getArea()+"\n拥有花园:"+this.garden;
		return str;
	}
}

测试类:

package duotai;

import java.util.Scanner;

public class HouseTest {

	public static void main(String[] args) {
		Scanner sr=new Scanner(System.in);
		System.out.print("请选择:1楼房  2.别墅 :");
		int num=sr.nextInt();
		HouseTest ht=new HouseTest();
		House h=ht.buy(num);
		System.out.println(h);

	}
		
		public House buy(int num) {
			if(num==1){
				House h=new LHouse("yh小区楼房", 50, "西航街道", 80, 20);
				return h;
			}else if(num==2){
				House h=new HHouse("yh别墅",1000,"政府右侧",300,3);
				return h;
			}
			return null;
		}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值