Java never declares access level of variables in m

2019-06-14 20:40发布

Today I suddenly realized that Java never specifies access level for local variables when I try to declare a variable for main method. I also tried to give it a access level modifier, but it doesn't compile. The error is: Illegal modifier for parameter t1; only final is permitted

package myThread;

import java.lang.Thread;
import java.lang.String;
import java.lang.System;

public class PrintThread extends Thread{ //extends Thread class

    private long sleepTime;

    public PrintThread(String name)
    {
        super(name);
        this.sleepTime = (long) (java.lang.Math.random() * 5000);

        System.out.println("Thread: " + getName() + ", sleepTime: " + sleepTime);
    }

    public void run() // override run method
    {
        System.out.println(getName() + " go to sleep...");
        try
        {
            sleep(sleepTime);
        } catch (InterruptedException e)
        {
            e.getMessage();
        }
        System.out.println(getName() + " out of sleep!");
    }

    public static void main(String[] args)
    {
        public PrintThread t1 = new PrintThread("T1"); // CANNOT COMPILE
        t1.start(); // start thread by start() method
    }
}

As we know, we need to use public protected package private static final etc to specify a member variable of java class.

But we never do this for class method (static or not) variable.

I was stuck with this conception all day. Previously, I just write java code as usual but didn't realize this phenomenon.

Could you give me hints. I CANNOT persuade myself just by eliminate public keyword for t1.

3条回答
【Aperson】
2楼-- · 2019-06-14 21:12

the scope for Method variables is limited to that method. this mean reference is created on the stack when method started/variable declared and destroyed as soon as method ends.

Allowing it to be public or any other access specifier wont be any good as the field will not exist outside of method.

another question how will you access them outside method?

class A{
   public String s="test";
   void myMethod(){
     public String s=this.s+"not allowed"; // If allowed how will you access the local s variable outside of method??? 
   } 

So allowing those access specifier is not allowed by compiler becuase there is no use of declaring them.

查看更多
相关推荐>>
3楼-- · 2019-06-14 21:22

Because it doesn't make sense. Variables declared in a method are local to the method; i.e. they can't be accessed outside the method. Why and how could these variables be modified outside the method? Code outside the method doesn't even know of them, so you don't need to protect them from outside code.

查看更多
再贱就再见
4楼-- · 2019-06-14 21:22

you can't add access modifier inside the method, because it belongs only to that method where you created the variable. so there is no use to add access modifier in the method

查看更多
登录 后发表回答