繁体   English   中英

如何在不同类的另一个实例方法中引用实例方法?

[英]How to reference an instance method in another instance method of a different class?

如果一个类是在另一个类的方法中实例化的,而另一个类的方法是在main方法中实例化的第三个类中的,则无法在这里找到它。 我知道最后的陈述冗长而令人困惑。 因此附上代码以更好地理解。

public class B {
private String name;
public void setname(String name){
    this.name=name;
}
public String getname(){
    return name;
}

}

public class C {void method2(){
B b = new B();
b.setname("BBB");

}

}

public class A {void method1(){
B b=new B();
b.setname("AAA");
C c= new C();

System.out.println(b.getname());

}

}

public class Testcase {

/**
 * @param args
 */
public static void main(String[] args) {
    A a=new A();
    a.method1();

}

}

如何来指代getName()方法从对象B在对象C实例化。

像这样将您的类实例设置为公开:

public B b = new B();
public C c = new C();

现在,您可以像这样访问它们:

a.b.c.getName();

将类实例设置为public是错误的,因为:

  • 所有公开的东西都必须经过测试。
  • 它破坏了封装
  • 有更好的方法来做到这一点

您需要做的是添加wrapper method

例如在C类中:

public class C {
    private B b;
    void method2(){
        b = new B();
        b.setname("BBB");
    }
    public void setName(String newName)
    {
         b.setname(newName);
    }
    public String getName()
    {
         return b.getName();
    }
}

公共实例方式:

public class C {
    public B b = new B();
    void method2(){
        b.setname("BBB");
    }
}

public class A {
    public C c = new C();
    public B b =new B();
    void method1(){
        b.setname("AAA");

        System.out.println(b.getname());
    }
}
public class Testcase {
    public static void main(String[] args) {
        A a=new A();
        a.c.b.setname("tralala");

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM