0

我是 Java 新手。所以这个问题可能看起来很幼稚......但是你能帮忙吗?

例如,我有一个类如下:

public class Human {

    private float height;
    private float weight;
    private float hairLength;

    private HairState hairTooLong = new HairState() {

        @Override
        public void cut(Human paramHuman) {         
            Human.this.decreaseHairLength();
        }

        @Override
        public void notCut(Human paramHuman) {
            Human.this.increaseHairLength();
        }
    };

    public float increaseHairLength () {
        hairLength += 10;
    }

    public float decreaseHairLength () {
        hairLength -= 10;
    }

    private static abstract interface HairState {

        public abstract void cut(Human paramHuman);
        public abstract void notCut(Human paramHuman);
    }       
}

然后我有另一个类如下:

public class Demo {
    public static void main(String[] args) {    
        Human human1 = new Huamn();
        Human.HairState.cut(human1);
    }
}

该声明

Human.HairState.cut(human1);

是无效的...

我打算调用属于私有属性的公共函数。 cut()hairTooLong

我该怎么做?

4

3 回答 3

8

由于HairState是私有的Human,因此课堂之外的任何人Human都无法知道它。

您可以创建一个方法Human,将调用中继到其私有机制:

public class Human {
    . . .

    public float cutHair() {
        return hairTooLong.cut(this);
    }
}

然后从以下位置调用main()

System.out.println(human1.cutHair());
于 2013-05-30T03:18:53.943 回答
1

先前评论的另外两个解决方案:

  • 您可以实现一个返回 hairTooLong 属性的 getter。
  • 您可以通过反射 API 调用 cut() 方法(但如果您是初学者,则不想去那里)。

将建议上一条评论中的解决方案,或此处提供的第一个选项。

如果您好奇,可以查看反射 API 和此处的示例:How do I invoke a Java method when given the method name as a string?

于 2013-05-30T03:30:14.877 回答
1

在java中有四种访问级别,默认、私有、公共和受保护。private 的可见性仅限于某个类(即使是子类也无法访问)。您不能调用任何其他类中的私有成员。这是java访问级别的基本细节。

                 Access Levels
Modifier    Class   Package  Subclass World
public        Y        Y        Y       Y
protected     Y        Y        Y       N
no modifier   Y        Y        N       N
private       Y        N        N       N

有关更多详细信息,请查看Oracle 文档

于 2013-05-30T04:15:18.067 回答