Resolving Class and Local Variable Name Clash
Methods to rightly use variable names when their names clash between class/static types and local types.
Learning Objectives
- Techniques to reuse variable names even if their names clash between static declaration and local declaration.
Source Code
|
Run Output
Code Understanding
class VariableNameClash
{
static int x=10;
This is a class variable with name x.
public static void main(String[] args)
{
int x=20;
This is a local variable with same name x;
System.out.println(x);
The local variable can be used directly
//System.out.println(this.x);
The static variable can be used using the this keyword if the method is not static type. If we remove static modifier of main we can use this type.
System.out.println(VariableNameClash.x);
Using the class name prefix we can directly use the static variable within the local context also.
}
}
Suggested Filename(s): VariableNameClash.java
sunmitra| Created: 20-Mar-2018 | Updated: 20-Mar-2018|