简体   繁体   中英

Java: Access Modifier Confusion

According to this tutorial in the Java documentation, public members can be accessed on the Class, Package, Sublcass, and World levels. But say I create two classes like so:

public class TesterClass
{
    public int someNumber = 5;
}

public class AnotherClass
{
    public static void main( String [] args )
    {
         System.out.println( someNumber );
    }
}

and save them in the same location. When AnotherClass is compiled, an error is thrown saying that the variable someNumber cannot be recognized. Why, then, does the Java docs state that public access modifiers allow access everywhere? I understand that I am doing something wrong, but what exactly is going on?

Those two classes are not related in any way, shape, or form.

You need to create an instance of the TesterClass in AnotherClass , then access the variable via the reference.

public class AnotherClass
{
    public static void main( String [] args )
    {
         TesterClass classRef = new TesterClass();
         System.out.println(classRef.someNumber);
    }
}

This will work and produce an output of 5.

However, if we changed the access modifier of the count variable from public to private and then attempted to do the same thing, this would no longer work. The count variable would be inaccessible to any other class except the class that declares it.


To expand upon Sotirios Delimanolis's comment, consider the following Scenario:

public class TesterClass
    {
        public int someNumber = 5;
    }

    public class CounterExampleClass
    {
        public int someNumber = 3;
    }

    public class AnotherClass
    {
        public static void main( String [] args )
        {
             System.out.println( someNumber );
        }
    }

According to your logic, what would be printed 3 or 5? You cannot say. Hence the variables are accessed via a reference variable, the reference class indicates which fields can be accessed. Ie

    TesterClass tRef = new TesterClass();
    tRef.someNumber; //5

    CounterExampleClass cRef = new CounterExampleClass();
    cRef.someNumber; //3

The variable you referencing is bound to bring errors as it is not recongised in that class, create first an instance of TesterClass

    TesterClass testObj=new TesterClass();
//then call println 
System.out.println(testObj.someNumber);

Never use variables you havent declared!!...Happy coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM