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

public であると宣言したのと同じように、キーワードcountを使用するだけで、同じように保護されるように変更できます。protected

protected static int count = 0;

これにより、拡張されていない他のパッケージのクラスが直接Productアクセスできなくなることに注意してください。ただし、パブリックであるため、メソッドcountからその値を取得することはできます。getCount()保護するように変更したい場合は、キーワードを変更するだけで再度行うことができます。

protected static int getCount()
{
    return count;
}
于 2012-07-23T05:09:20.493 に答える
0

あなたが今持っているあなたの変数:

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

カウント変数をパブリックではなく保護する場合は、次のようにする必要があります。

private String code;
private String description;
private double price;
protected static int count = 0;
于 2012-07-23T05:13:55.033 に答える
-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 に答える