Java如何在方法内部获取变量,反之亦然

Java如何在方法内部获取变量,反之亦然,java,variables,methods,Java,Variables,Methods,有人能告诉我如何在方法内部得到变量,反之亦然。 比如: 我想在方法func中使用变量y,从方法func中得到x,然后在main中使用它 class test{ int y = 4; void func(){ int x = 3; } public static void main(String[] args) { // take x inside main }} 或者,您可以将func()方法设为静态,这样您就可以在不创建类的对象的情况下调用此方法: class test{ int y

有人能告诉我如何在方法内部得到变量,反之亦然。 比如: 我想在方法func中使用变量y,从方法func中得到x,然后在main中使用它

class test{
int y = 4;

void func(){
int x = 3;
}

public static void main(String[] args)
{
// take x inside main
}}
或者,您可以将func()方法设为静态,这样您就可以在不创建类的对象的情况下调用此方法:

class test{
 int y = 4;

 static int func(){
  int x = 3;
  return x;
 }

 public static void main(String[] args)
 {

   int x = func();
  }
}
y应可在函数内部访问。如果函数本身使用变量y,则可以使用此.y访问该变量

通过调用test.y,将其设置为静态,这样您就可以随时随地访问它

class test{
    public static int y = 4;

    void func(){
       int x = 3;
    }
}
然后你可以在主要的地方做这件事

public static void main(String[] args)
{
    int value = test.y;
}

试着这样做:

   class Main {
    public int y= 4;
    int func(){
    return 4;
    }
    public static void main(String... args){
    Main m = new Main();
    int x = m.func();
    int y = m.y;

}
}

您始终可以在方法内部使用类变量。要在main()方法中使用func()的x,可以从func()返回它或将其保存到某个类变量中

class TestClass {
int y = 4;
int x = 0;

//func returning x
int func1() {
    int x = y;
    return x;
}

//func storing it to class variable
void func2() {
    this.x = 3;
}

public static void main(String[] args) {
    TestClass t = new TestClass();
    int xOfFunc = t.func1();

    t.func2();
    System.out.println("x Of Func :: " + xOfFunc + "\n class variable x :: " + t.x);
    }
}
输出:

x Of Func :: 4 
class variable x :: 3

更改func的签名并使其返回int。您可以在func之外使用x,因为这是函数的一个局部属性。如果要在主函数中使用,请将其设为类的静态变量,并将func设为静态或创建类test的实例,然后调用返回x的func
class TestClass {
int y = 4;
int x = 0;

//func returning x
int func1() {
    int x = y;
    return x;
}

//func storing it to class variable
void func2() {
    this.x = 3;
}

public static void main(String[] args) {
    TestClass t = new TestClass();
    int xOfFunc = t.func1();

    t.func2();
    System.out.println("x Of Func :: " + xOfFunc + "\n class variable x :: " + t.x);
    }
}
x Of Func :: 4 
class variable x :: 3