如何在java中添加受保护的变量

时间:2012-07-23 05:06:34

标签: java java-7

我需要将一个受保护的变量添加到我拥有的产品类文件(我已经附加了该文件的当前代码)。我需要将count变量的访问修饰符从public更改为protected。 我怎么做?!我需要在下面的代码中添加一些保护变量:

import java.text.NumberFormat;

public class Product
{
    private String code;
    private String description;
    private double price;
    public static int count = 0;

    public Product()
    {
        code = "";
        description = "";
        price = 0;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getCode(){
        return code;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }

    public String getDescription()
    {
        return description;
    }

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

    public double getPrice()
    {
        return price;
    }

    public String getFormattedPrice()
    {
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        return currency.format(price);
    }

    @Override
    public String toString()
    {
        return "Code:        " + code + "\n" +
               "Description: " + description + "\n" +
               "Price:       " + this.getFormattedPrice() + "\n";
    }

    public static int getCount()
    {
        return count;
    }
}

3 个答案:

答案 0 :(得分:0)

正如您宣布count已公开一样,您只需使用protected关键字即可以相同的方式将其更改为受保护:

protected static int count = 0;

请注意,这会阻止来自未扩展Product的其他包的类直接访问count。但是,他们仍然可以从getCount()方法获得其价值,因为这是公开的。如果您希望更改要保护的内容,只需更改关键字即可再次执行此操作:

protected static int getCount()
{
    return count;
}

答案 1 :(得分:0)

您现在拥有的变量:

private String code;
private String description;
private double price;
public static int count = 0;

如果您希望count变量受保护而不是public,则应该是:

private String code;
private String description;
private double price;
protected static int count = 0;

答案 2 :(得分:-1)

试试这个

  public static void main(String[] args)
  {
     Product p=new Product(); 
     Class productClass = p.getClass(); 
     Field f = productClass.getDeclaredField("count"); 
     f.setAccessible(false); //Make the variable non-accessible
  }