[英]How can we pass variables from one method to another in the same class without taking the help of parent class?
讓我們看一個像這樣的簡單程序:
public class Dope
{
public void a()
{
String t = "my";
int k = 6;
}
public void b()
{
System.out.println(t+" "+k);/*here it shows an error of not recognizing any variable*/
}
public static void main(String Ss[])
{
}
}
雖然我可以通過這種方式糾正它:
public class Dope
{
String t;
int k ;
public void a()
{
t = "my";
k = 6;
}
public void b()
{
System.out.println(t+" "+k);
}
public static void main(String Ss[])
{
}
}
但我想知道在我以前的程序中是否有任何method a
將method b
聲明的變量傳遞給method b
而不需要父類的幫助?
您可以使用兩個參數聲明b方法,如下例:
public class Dope
{
public void a()
{
String t = "my";
int k = 6;
b(t, k);
}
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
public static void main(String Ss[])
{
}
}
將方法的簽名從b()
更改為b(String t,int k)
public void b(String t, int k)
{
System.out.println(t+" "+k);
}
並從方法a()
調用b(String t,int k)
a()
通過使用這些方法參數,您無需更改變量的范圍。
但是請記住,每當您在Java中將某些內容作為參數傳遞時,它都會作為按值調用的形式傳遞。
我有兩個方法,一個布爾值和一個靜態void,我想在布爾方法中使用一個變量在靜態void方法中創建一個切換條件。 任何幫助請?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.