如何访问抽象超类实例变量

时间:2013-11-18 15:28:29

标签: java subclass abstract super

所以我有两个课程:PropertyHousesProperty是抽象超类,Houses是它的子类。

以下是Property

的代码
public abstract class Property{
     String pCode;
     double value;
    int year;

    public Property(String pCode, double value , int year){
        this.pCode = pCode;
        this.value = value;
        this.year = year;
    }

        public Property(){
            pCode = "";
            value = 0;
            year = 0;
        }
    public abstract void depreciation();

    //Accessors
    private String getCode(){
        return pCode;
    }
    private double getValue(){
        return value;
    }
    private int getYear(){
        return year;
    }
    //Mutators
    private void setCode(String newCode){
        this.pCode = newCode;
    }
    private void setValue(double newValue){
        this.value = newValue;
    }
    private void setYear(int newYear){
        this.year = newYear;
    }

    public String toString(){
        return ("Code: " + getCode() + "\nValue: " + getValue() + "\nYear: " + getYear());
    }
}

以下是Houses

的代码
public class Houses extends Property{
    int bedrooms;
    int storeys;


    public Houses(){
        super(); // call constructor
        this.bedrooms = 0;
        this.storeys = 0;
    }

    public Houses(String pCode , double value , int year ,int bedrooms , int storeys){
                super(pCode,value,year);
        this.bedrooms = bedrooms;
        this.storeys = storeys;
    }
    //accessors
    private int getBedrooms(){
        return bedrooms;
    }
    private int getStoreys(){
        return storeys;
    }
    private void setBedrooms(int bedrooms){
        this.bedrooms = bedrooms;
    }
    private void setStoreys(int storeys){
        this.storeys = storeys;
    }

    public void depreciation(){

            this.value = 95 / 100 * super.value;
            System.out.println(this.value);
    }
        public String toString(){
        return (super.toString() + "Bedroom:" + getBedrooms() + "Storeys:" + getStoreys());
    }

}

我现在的问题是,在方法depreciation中,每当我尝试在main方法中运行它时,如下所示

    public static void main(String[] args) {
        Houses newHouses = new Houses("111",20.11,1992,4,2);
        newHouses.depreciation();
     }

打印出0.0。为什么不打印20.11?我该如何解决?

============================================== < / p>

编辑:感谢您修复我的愚蠢错误&gt;。&lt;

但是,我只想说我的财产正在使用

          private String pCode;
          private double value;  
          private int year;

现在我无法访问它们,因为它们是私有访问权限,有没有其他方法可以访问它们?

3 个答案:

答案 0 :(得分:6)

那是因为95 / 100是一个整数除法,结果产生0。试试

0.95 * super.value

95.0 / 100 * super.value

答案 1 :(得分:1)

而不是:

 this.value = 95 / 100 * super.value;

你应该:

 this.value = 95d / 100d * super.value;

95/100导致int值为0.

答案 2 :(得分:0)

在我的手机上,所以我无法做适当的代码块,但现在就去了。

private int x;

public int getX() {
    return x;
}