0

I am new to Java. So the question may seem naive... But could you please help?

Say for example, I have a class as follows:

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);
    }       
}

Then I have another class as follow:

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

The statement

Human.HairState.cut(human1);

is invalid...

I intend to call the public cut() function, which belongs to hairTooLong private attribute.

How should I do it?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174

3 Answers3

8

Since HairState is private to Human, nothing outside the Human class can even know about it.

You can create a method in Human that relays the call to its private mechanism:

public class Human {
    . . .

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

and then call that from main():

System.out.println(human1.cutHair());
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

Two other solutions to previous comment:

  • You can implement a getter which returns the hairTooLong attribute.
  • You can invoke the the cut() method through the reflection API (but you don't want to go there if you are beginner).

Would suggest either the solution in the previous comment, or the first option presented here.

If you are curious, you can have a look to the reflection API and an example here: How do I invoke a Java method when given the method name as a string?

Community
  • 1
  • 1
clement
  • 1,491
  • 2
  • 10
  • 11
1

In java there are four access levels, default, private, public and protected. Visibility of private is only limited to a certain one class only (even subclass cannot access). You cannot call private members in any other class. Here is a basic details of java access levels.

                 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

For more details check Oracle docs