Voldemort
Voldemort

Reputation: 181

Can you access a private variable of an instance if it is in the same class? (copyOf)

As an example,

public class SwapNumbers {

private int aNumber = 0; ///////////////////////////////////

    public SwapNumbers(){

    }

    public void changeNumber(int changed){
    aNumber = changed;

    }
    public void swap(SwapNumbers otherNumber){ ///////////

    aNumber = otherNumber.aNumber; //Can we access aNumber?
    }


}

would the swap in this work? My first instinct was that it would not work because it is trying to access a private value.

Upvotes: 0

Views: 112

Answers (2)

drew moore
drew moore

Reputation: 32670

Yes. making a member private means it is available to the current class along with any of its inner-classes, subject to static qualifiers.

Package-private (or the default, without any access modifiers) means it is available to any class in the same package.

the public modifier makes it available to any class in any package anywhere. Be careful with these :)

Upvotes: 4

Tough Griff
Tough Griff

Reputation: 48

If you are within the same class, you will have no problems accessing any variables within the class--private, protected, or public.

You will only be unable to access private variables from outside

public class SwapNumber {
...
}

Upvotes: 0

Related Questions