Variables having same name but different type

后端 未结 4 1375
无人及你
无人及你 2020-12-09 23:32

I have read here that in Java it is possible for two variables having same name but different type to co-exist in the same scope. What I mean is this

class te         


        
4条回答
  •  天命终不由人
    2020-12-10 00:15

    You cannot have variables having same name (but different type) to exist in the same scope. Consider if it was possible then how would the java compiler determine which one you meant.

    Consider this code snippet

    class test
    {
        private int x;
        private double x;
    
        test() //constructor
        {
            System.out.println(x); //Error cannot determine which x you meant
        } 
    }
    

    The java compiler cannot understand which x you are actually referring to. So such a code is not syntactically correct and not compilable.

    However there exists tools such as ClassEditor which can modify the generated class file after it is created. There it is possible to change the name two variables to same.

    However such a class is not necessarily runnable by the java jvm.

    The software which you have quoted i.e JAD can rename such duplicate named variables in the class file so that the source code which you will be getting will actually be syntactically correct

提交回复
热议问题