1

我需要在我拥有的产品类文件中添加一个受保护的变量(我已附加该文件的当前代码)。我需要将 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;
    }
}
4

3 回答 3

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;
于 2012-07-23T05:13:55.033 回答
0

正如您已声明为 public 一样,您可以通过使用关键字count以同样的方式将其更改为受保护:protected

protected static int count = 0;

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

protected static int getCount()
{
    return count;
}
于 2012-07-23T05:09:20.493 回答
-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
  }
于 2012-07-23T05:14:47.660 回答