目的:使用父类作为方法返回值来实现多态
运行效果:
父类:
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;
}
}