我尝试为希望为物业缴纳年度税的当地登记人员制定一种算法。我有一个用于Properties的抽象类,该类具有用于其他类型属性的基本变量和方法。问题是,我想为一个已知的客户端打印所有属性,但我不知道如何通过超类获取属性的类型
我考虑过要在Properties类中声明另一个变量,该变量将告诉我是否有范围,然后知道了,我将拥有Building或Field。但这并不尊重多态性。如果要引入一种新型的属性,则需要更改所有内容。 我对java很陌生,没有其他线索。谢谢。
public class Client {
private int CNP;
private String Name;
private int totalSum;
private Properties[] properties;
public Client(String Name, Properties[] properties) {
this.Name = Name;
this.properties = properties;
setTotalSum(properties);
CNP = 0;
}
public Client(int CNP, Properties[] properties) {
Name = "No Name Specified";
this.properties = properties;
setTotalSum(properties);
this.CNP = CNP;
}
public Client(String Name, int CNP, Properties[] properties) {
this.Name = Name;
this.properties = properties;
setTotalSum(properties);
this.CNP = CNP;
}
public String toString() {
String s = "Contribuabil: " + getName() + "\n" +
"Proprietati: \n";
for(Properties property:properties) {
s += property.toString();
}
s += "Suma totala: " + getTotalSum();
return s;
}
属性类
abstract class Properties {
private String nameAdress;
private int number;
private int paySum;
public Properties(String nameAdress, int number) {
this.nameAdress = nameAdress;
this.number = number;
}
public void setPaySum(int surface) {
paySum = 500 * surface;
}
public void setPaySum(int surface, int rang) {
paySum = (350 * surface) / rang;
}
public int getPaySum() {
return paySum;
}
public String toString() {
//here I would like to print the type of property;
}
子类建筑物
public class Building extends Properties {
private int surface;
public Building(String nameAdress, int number, int surface) {
super(nameAdress, number);
this.surface = surface;
setPaySum(surface);
}
子类字段
public class Field extends Properties {
private int surface;
private int rang;
public Field(String nameAdress, int number, int surface, int rang) {
super(nameAdress, number);
this.surface = surface;
this.rang = rang;
setPaySum(surface, rang);
}