有人可以告诉我如何获得方法内的变量和相反。 类似于: 我想在该方法func中使用变量y,并从该方法func获取该x并在main中使用它。Java我怎样才能得到一个方法内的变量和相反
class test{
int y = 4;
void func(){
int x = 3;
}
public static void main(String[] args)
{
// take x inside main
}}
有人可以告诉我如何获得方法内的变量和相反。 类似于: 我想在该方法func中使用变量y,并从该方法func获取该x并在main中使用它。Java我怎样才能得到一个方法内的变量和相反
class test{
int y = 4;
void func(){
int x = 3;
}
public static void main(String[] args)
{
// take x inside main
}}
class test{
int y = 4;
int func(){
int x = 3;
return x;
}
public static void main(String[] args)
{
test obj = new test();
int x = obj.func();
}
}
,或者你可以让FUNC()方法,静态,你将能够调用此方法,而无需创建类的一个对象:
class test{
int y = 4;
static int func(){
int x = 3;
return x;
}
public static void main(String[] args)
{
int x = func();
}
}
class test{
int y = 4;
int x;
void func(){
int x = 3;
this.x = 3; //make it usable from the class
}
}
Ÿ应该可以访问内部功能。如果函数本身使用变量y,则可以使用this.y来访问该变量。
使它像这样静态可以让你通过调用test.y来访问它。
class test{
public static int y = 4;
void func(){
int x = 3;
}
}
然后你可以在main中做到这一点。
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键更改签名,使它return int – Oscar
你可以在func外使用x,因为这是函数的本地属性。如果你想在主函数中使用。使其成为类的静态变量。 – Vikrant
使func静态或创建类测试的实例,然后调用func返回x –