Home > Software engineering >  Method and Variable Scope Issue in Java
Method and Variable Scope Issue in Java

Time:07-07

I need help I cannot figure out how to fix the scope of my variables. I want this to be an example for my notes but have been on it for almost 2 hours.

public class methodPractice{
    String streetName;
    int streetNum;
        public static void streetName()
    { 
         String streetName = "Pope Ave.";
    }
        public static void streetNum()
    {
        int streetNum = 11825;
    }
        public static void main(String[] args)
    {
        streetName();
        streetNum();
        System.out.println("This is your home adress: "   streetNum   
        streetName);
    }
}

Thank you for your help.

CodePudding user response:

You are shadowing the fields. Use this to make sure you get the fields, or a compile error.

public static void streetName()
{ 
    this.streetName = "Pope Ave.";
}

public static void streetNum()
{
    this.streetNum = 11825;
}

CodePudding user response:

Here is your main method, with line numbers added:

1.    public static void main(String[] args) {
2.       streetName();
3.       streetNum();
4.       System.out.println("This is your home adress: "   streetNum   streetName);
5.    }

A few points...

  • When line 2 runs, "streetName()" calls the static method below. The static keyword says you are free to call the method by itself – that is, you don't need an object; you don't need to call new methodPractice() first.

    public static void streetName() {
        String streetName = "Pope Ave.";
    }
    
  • When line 3 runs, it's the same thing: "streetNum()" calls a different static method – again, totally fine to call this by itself.

    public static void streetNum() {
        int streetNum = 11825;
    }
    
  • Line 4 is different, there are a few things going on. Your expectation is that "streetNum" finds the int that you declared on the class, but it doesn't work. Why? Because you defined that member with "int streetNum" – without "static". So what? Without being declared static, it means "streetNum" belongs to an object instance. What does that look like? Here's an example showing object creation, followed by setting the object member "streetNum" to 1.

    methodPractice object = new methodPractice();
    object.streetNum = 1;
    

You could work around this by declaring both of the non-static members to be static (static String streetName, and static int streetNum). Or you could leave them as is, and interact with them through an object instance (after doing new ..).

  • Related