2012-07-23 68 views
1

我需要一个受保护的变量添加到产品类文件添加一个受保护的变量(i附上该文件的当前代码),我有。我需要将计数变量的访问修饰符从public更改为protected。 我该怎么做?!我需要什么样的变化的代码,使下面添加一个受保护的变量:如何用Java

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; 
    } 
} 
+0

这是你的作业吗? – Chakra 2012-07-23 05:09:15

回答

0

正如你声明count是公开的,你可以改变仅仅通过它来进行保护以同样的方式多protected关键字:

protected static int count = 0; 

注意,这会阻止那些不直接访问count延长Product其他包中的类。但是,它们仍然能够从getCount()方法中获得它的价值,因为这是公开的。如果你想改变,要得到保护,你可以通过更改关键字再次这样做:

protected static int getCount() 
{ 
    return count; 
} 
+0

是的,我也一样! :) 谢谢。我只知道自己!很高兴! :) – 2012-07-23 05:17:21

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; 
+0

谢谢Mathagan。为什么人们会像你的家庭作业一样写废话。是的,如果你陷入困境,你需要人们的帮助,那么!哇。你知道我明白了什么。非常简单! :P愚蠢的我 – 2012-07-23 05:16:24

+0

笑我猜人们好奇 – Matthagan 2012-07-23 05:35:52

-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 
    } 
+0

有没有必要做这个使用反射... – 2012-07-23 05:15:28

+0

我还以为他是在谈论运行时的变化... :) – 2012-07-23 05:15:50