javaobjectobject-oriented-analysis

Why is it in java I have to prepend the class name to static variable to access it from outside the class. Looking to understand the compiler


So in java you write a public static variable and you have to access it outside of the class by saying class.var I find it strange that you can't access it by just by typing the variable name if your package is included in the main file.

Looking for an understanding of how the compiler works on java and object oriented languages that use this same class.publicstatic methodology.


Solution

  • You can have static variables with the same name within different classes. It is possible that you will encounter an error in this request that you make without specifying a class name. to give an example ;

    package com.axample;
    import ...
    
    public static class FooClass{
        public static int staticVariable;
        .
        .
        .  
    }
    package com.axample;
    import ...
    
    public static class BarClass{
        public static int staticVariable;
        .
        .
        .  ​
    }
    
    
    import static com.example.FooClass.*;
    import static com.example.BarClass.*;
    
    public class Main{
        public static void Main(String[] args){
            int baz = 0;
            //staticVariable = baz ;   //Error
            BarClass.staticVariable = baz;  //Must be
        } ​
    }