Java - 有一个方法可以将私有(private)字段值传递给另一个类的方法吗?

标签 java class parameter-passing field private-members

我有一个包含大量字段的类,所有字段都是私有(private)的(子类访问一些 protected getter)。我需要将这些字段中的大部分传递给另一个类中的方法,该方法将格式化它们并生成输出。在类中有一个方法可以传递所有的字段吗?或者这些情况是否表明我应该在这两个类之间实现一些其他关系,因为它们因此看起来紧密耦合?

更多信息:A 类代表 Employees,B 类的唯一职责是格式化程序的输出。

最佳答案

您是在问是否可以执行以下操作?

public class A {
 private B myB = new B();
 private String myUnformattedName = "some information";

 public String getFormattedInfo() {
   return myB.formatInfo(myUnformattedName);
 }
}

那完全没问题。

Marking a field as private just means that only the containing class should be able to access it...

如果你的意思是别的,最好在你的问题中弹出一些代码来给人们提供上下文


好的,所以无法在此处设置值,但您可以在此处看到调用格式化程序的两种不同方式。当参数列表超过三项或四项时,就会变得难以阅读。

在这种情况下,我只是将 A 传递给格式化程序,并为您希望 B 能够读取的每个值提供一个 get 方法。

public class A {
 private B myB = new B();
 private String myUnformattedName = "some information";
 private String myUnformattedNameOne = "some information";
 private String myUnformattedNameTwo = "some information";
 private String myUnformattedNameThree = "some information";
 private String myUnformattedNameFour = "some information";
 private String myUnformattedNameFive = "some information";
 private String myUnformattedNameSix = "some information";

 public String getFormattedInfo() {
   //pass the object itself and use get methods
   return myB.formatInfo(this); 
 }

 public String getFormattedInfoLong() {
   //this is OK but gets difficult to read the longer the 
   //parameter list gets
   return myB.formatInfo(myUnformattedName, myUnformattedNameOne, 
      myUnformattedTwo, myUnformattedNameThree, myUnformattedNameFour,
      myUnformattedNameFive, myUnformattedNameSix); 
 }

 //getters
 public String getUnformattedName() {
    return myUnformattedName;
 }

 public String getUnformattedNameOne() {
    return myUnformattedNameOne;
 }

 //etc

}

关于Java - 有一个方法可以将私有(private)字段值传递给另一个类的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899468/

相关文章:

java - "Failed to initialize App Engine SDK at [path]"是什么意思,如何解决?

c++ - 删除类内部成员函数中的对象

Excel 电力查询 : Parameter value from certain cell

java - jackson 错误解析器尝试解析子类型,但我的类(class)是简单的POJO

java - 如何使用java中的位操作来缩短长值?

Java加载资源Class.class.getResource vs <classname>.class.getResource

python - Django url参数传递

java - 使用类读取txt文件

C# 构造函数有 2 个参数,但声称它没有带两个参数的构造函数

c++ - 可变函数模板 : automating N inputs at run time based on N compile time value