【问题标题】:Can a private member of a new object be accessed from inside a method in the class definition of that object?可以从该对象的类定义中的方法内部访问新对象的私有成员吗?
【发布时间】:2015-12-04 05:50:05
【问题描述】:

这就是我的类定义的方式:

public class ArrayBag implements Bag {
    /** 
     * The array used to store the items in the bag.
     */
    private Object[] items;

    /** 
     * The number of items in the bag.
     */
    private int numItems;

...等等...

这是类定义中的一个方法,这个类的新对象是在方法内部创建的:

 //creates and returns an Arraybag that is the union of the called Arraybag and the parameter bag
 public bag unionWith(Bag other) {

     if (other == null)
           throw new IllegalArgumentException(); 

     int cap = this.capacity() + other.capacity();

     //new object created here      
     ArrayBag newbag = new ArrayBag(cap);

     for (int i = 0; i < numItems; i++) {

           if (other.contains(items[i])) 

                 newbag.add(items[i]);

     }

     for (int i = 0; i < newbag.numItems(); i++)

        //Can I use "newbag.items[i]"?
        if (numOccur(newbag.items[i]))


 }

我的问题是,我可以从这个方法定义中访问 newbag 对象的 Object[] 项吗?像这样:newbag.items[i]

【问题讨论】:

  • 为什么不测试一下自己呢?您已经编写了示例。

标签: java inheritance private


【解决方案1】:

您可以访问它。

这样做是可行的:

public class AClass {
    private int privateInteger;
    public AClass() {
        privateInteger = 5;
    }
    // First way 
    public void accessFromLocalInstance() {
        AClass localInstanceOfClass = new AClass()
        int valueOfLocalInstance = localInstanceOfClass.privateInteger;
    }
    // Second way
    public void accessFromInstance(AClass instance) {
        int valueOfInstance = instance.privateInteger;
    }
}

因为

“private”表示仅限于该类,不限制于该对象。

Access private field of another object in same class

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2017-01-16
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多