public class RentalApt extends Apartment{
private String tenant;
private boolean rented;
public RentalApt(String owner, int size, boolean rented, String who){
super(owner,size);
tenant = who;
this.rented = rented;
}
public boolean getRented(){
return rented;
}
public String getTenant(){
return tenant;
}
public void setRented(boolean isRented){
rented = isRented;
}
public void setTenant(String who){
tenant= who;
}
public String toString(){
String s = super.toString();
return (s + " occupied? " + rented + " tenant: " + tenant);
}
}
假设您创建一个从 RentalApt 类派生的新 PricedApt 类(因此它是从派生类派生的)。它添加了一个新的双重属性,即价格,它告诉我们公寓的月租金是多少。这是该类的构造函数调用:
PricedApt p = new PricedApt("jill", 900, true, "jack", 1050.00);
适本地使用 super,为该类编写一个 toString 方法,除了告诉 jill 作为所有者和 jack 作为租户之外,还向 toString 输出添加短语“price:”+price。 (注意:PricedApt 中对 toString 的 super 调用将使用其基类 RentalApt 中的 toString 方法。
public class PricedApt extends RentalApt {
private double price;
public String toString() {
//code
所以我知道我需要回收 RentalApt 中的 toString() 方法,但我在租用和租户方面遇到错误,因为它们是私有(private)的。我已经尝试了我所知道的一切,但我还没能克服这个错误。这是我到目前为止所拥有的:
public String toString() {
String s = super.toString();
return (s + " occupied? " + rented + " tenant: " + tenant+ " price: " + price);
}
我尝试过使用关键字 super 进行一些操作,但没有成功。很抱歉这个问题:我知道以前已经回答过这个问题,但我从过去的答案中看不到任何东西可以解决我的基本问题。
最佳答案
PricedApt.toString()
应仅引用 price
和 RentalApt.toString()
。
您的做法是正确的,只需从 PricedApt.toString()
中删除 rented
和 tenant
关于java - 如何在不使用访问器的情况下访问父类(super class)中的私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324778/