从另一个 class 创建的调用对象
Call object created from another class
我需要 ClassB
来获取从 ClassA
创建的对象,即 u
。我怎么做? ClassA
使用 setSomething()
从 Utility
class 设置值,而 ClassB
应该使用 getSomething()
获取 ClassA
设置的值同一个对象(u
)
public class ClassA
{
Utility u = new Utility()
u.setSomething("David");
}
public class ClassB
{
//How do I get the 'u' Utility object from ClassA
}
public class Utility
{
private String fullName;
public void setSomething(String name)
{
this.fullName = name
}
public String getSomething()
{
return fullName;
}
}
没有模式和简单的直接方法 类。
public class ClassA {
private Utility u = new Utility()
public ClassA() {
u.setSomething("David");
}
public Utility getU() {
return u;
}
}
public class ClassB {
private ClassA classA = new ClassA();
public ClassB() {
System.out.println(classA.getU().getSomething());
}
}
public class Utility {
private String fullName;
public void setSomething(String name) {
this.fullName = name;
}
public String getSomething() {
return fullName;
}
}
public static void main(String[] args) {
ClassB b = new ClassB();
}
应该打印出来'David';
请注意,做事的方法不止一种。可以有一种方法可以做得更好。这完全取决于您的设计和需求,这只是一个示例:
public class ClassA{
Utility u = new Utility()
public Utility getU(){
return u;
}
public void buildB(){
ClassB classB = new ClassB(this);
}
}
public class ClassB{
ClassA classA;
Utility u;
public ClassB(ClassA classA){
this.classA = classA;
u = classA.getU();
}
}
我需要 ClassB
来获取从 ClassA
创建的对象,即 u
。我怎么做? ClassA
使用 setSomething()
从 Utility
class 设置值,而 ClassB
应该使用 getSomething()
获取 ClassA
设置的值同一个对象(u
)
public class ClassA
{
Utility u = new Utility()
u.setSomething("David");
}
public class ClassB
{
//How do I get the 'u' Utility object from ClassA
}
public class Utility
{
private String fullName;
public void setSomething(String name)
{
this.fullName = name
}
public String getSomething()
{
return fullName;
}
}
没有模式和简单的直接方法 类。
public class ClassA {
private Utility u = new Utility()
public ClassA() {
u.setSomething("David");
}
public Utility getU() {
return u;
}
}
public class ClassB {
private ClassA classA = new ClassA();
public ClassB() {
System.out.println(classA.getU().getSomething());
}
}
public class Utility {
private String fullName;
public void setSomething(String name) {
this.fullName = name;
}
public String getSomething() {
return fullName;
}
}
public static void main(String[] args) {
ClassB b = new ClassB();
}
应该打印出来'David';
请注意,做事的方法不止一种。可以有一种方法可以做得更好。这完全取决于您的设计和需求,这只是一个示例:
public class ClassA{
Utility u = new Utility()
public Utility getU(){
return u;
}
public void buildB(){
ClassB classB = new ClassB(this);
}
}
public class ClassB{
ClassA classA;
Utility u;
public ClassB(ClassA classA){
this.classA = classA;
u = classA.getU();
}
}