提供两种方法.. 一种..直接持有 第一个类的 引用就行了. 第二种. 生成那个对象的 get set 方法. 获得到那个对象就行了.
class Goods { String string = new String ("ok"); public String getString() { return string; } public void setString(String string) { this.string = string; } }public class Person { public static void main(String[] args){ System.out.println(new Goods().getString()); } }这个很简单了吧 . person 调用 goods 里面的 String .. 我给用 get set 方法实现.. 很简单吧.
持有对方引用的例子 class Cls { String str; public Cls(String s){ this.str = s; } }public class Sysd { Cls c;//引用是成员 public Sysd(Cls c){ this.c = c; } public void printString(){ System.out.println(c.str); }
public static void main(String[] args) { Cls c = new Cls("Stirng in Cls"); Sysd s = new Sysd(c); s.printString(); }}
传递引用当作参数public class Sysd { public void printString(Cls c){ System.out.println(c.str); }
public static void main(String[] args) { Cls c = new Cls("Stirng in Cls"); Sysd s = new Sysd(); s.printString(c); }} class Cls { String str; public Cls(String s){ this.str = s; } }
String string = new String ("ok"); public String getString() {
return string;
} public void setString(String string) {
this.string = string;
}
}public class Person {
public static void main(String[] args){
System.out.println(new Goods().getString());
}
}这个很简单了吧 . person 调用 goods 里面的 String .. 我给用 get set 方法实现.. 很简单吧.
String str;
public Cls(String s){
this.str = s;
}
}public class Sysd {
Cls c;//引用是成员
public Sysd(Cls c){
this.c = c;
}
public void printString(){
System.out.println(c.str);
}
public static void main(String[] args) {
Cls c = new Cls("Stirng in Cls");
Sysd s = new Sysd(c);
s.printString(); }}
public void printString(Cls c){
System.out.println(c.str);
}
public static void main(String[] args) {
Cls c = new Cls("Stirng in Cls");
Sysd s = new Sysd();
s.printString(c); }}
class Cls {
String str;
public Cls(String s){
this.str = s;
}
}
"cls类中创建的有string对像s
现我要在sysd类中使用s这个对像" 将两个类放到同一个包中
在sysd中即可创建cls对象
其中的s 自然也可调用