【问题标题】:Set , Get Method in JavaJava 中的 Set , Get 方法
【发布时间】:2016-02-13 17:28:46
【问题描述】:

我刚刚开始接触 Java 中的面向对象编程。我很好奇下面两段代码之间的区别(如果有的话)。

public class BuyAHouseInc
{

    // Instance variables
    private String firstName;
    private String surname;
    private String address;
    private int budget;

    // method to set the first name in the object
    public void setFirstName(String firstName)
    {
        this.firstName = firstName; // stores the first name
    }

    // method to retrieve the first name from the object
    public String getFirstName()
    {
        return firstName; // return value of first name to caller 
    }

    // method to set the surname in the object
    public void setSurname(String surname)
    {
        this.surname = surname; // stores the surname
    }

    // method to retrieve the surname from the object
    public String getSurname()
    {
        return surname; // return the value of surname to caller
    }

    // method to set the address in the object
    public void setAddress(String address)
    {
        this.address = address; // stores the address
    }

    // method to retrieve the address from the object
    public String getAddress()
    {
        return address; // return the value of address to caller
    }

    // method to set the budget in the object 
    public void setBudget(int budget) 
    {
        this.budget = budget; // store the budget
    }

    // method to retrieve the budget from the object
    public int getBudget()
    {
        return budget; // return the value of address to caller
    }
}

这是第二段代码;

public class BuyAHouseInc
{    
    public void displayClient(String firstName, String surname, String address, int budget)
    {
        System.out.println("Client Name: " + firstName + " " + surname);
        System.out.println("Address: " + address);
        System.out.println("Budget: " + "€" + budget);
    }
}

我更喜欢这里的第二段代码,因为它更易于理解,但我已经阅读了很多关于方法和对象的内容,但我无法弄清楚实际的区别是什么。 set 和 get 方法是输入值的安全方法吗?

【问题讨论】:

  • 第二个代码与第一个代码无关...
  • 您可能想了解encapsulation 以了解您为什么要使用第一个代码
  • 这是一个关于 POJO 的好链接 en.wikipedia.org/wiki/Plain_Old_Java_Object ,您的 displayClient 方法看起来像一个 toString 方法 stackoverflow.com/questions/3615721/…
  • Set 和 get 方法使用封装,也就是私有变量只能从类中访问。我知道这一点,但是当两个代码都被编译时,它们对我的运行是一样的。
  • @eamonn-keogh 如果您看到相同的行为,则说明您正在运行此处未显示的代码。第一个代码块不打印任何内容到标准输出,但第二个 only 打印到标准输出。

标签: java oop methods


【解决方案1】:

让我们从你认为更简单的代码开始:

public class BuyAHouseInc
{    
    public void displayClient(String firstName, String surname, String address, int budget)
    {
        System.out.println("Client Name: " + firstName + " " + surname);
        System.out.println("Address: " + address);
        System.out.println("Budget: " + "€" + budget);
    }
}

我们可以实例化这个类并像这样使用它:

public static void main(String[] args) {
    BuyAHouseInc buyAHouseInc = new BuyAHouseInc();
    buyAHouseInc.displayClient("jane", "doe", "123 main street", 100000);
}

这个主要方法的作用是在你的屏幕上显示信息。这就是这个类的所有实例可以做的事情。您不能共享或重复使用这些信息。

您展示的第一段代码让您可以创建一个对象,其中包含可以重复使用的存储数据的字段。 getter 和 setter 是这样编写的,因此您可以访问这些字段以在程序的其他地方使用。

我们也可以在这个类中添加 displayClient 方法,像这样:

public class BuyAHouseInc {
    private String firstName;
    private String surname;
    private String address;
    private int budget;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getFirstName() {
        return firstName;
    }
    ...
    public void displayClient() {
        System.out.println("Client Name: " + this.firstName + " " + this.surname);
        System.out.println("Address: " + this.address);
        System.out.println("Budget: " + "€" + this.budget);
    }
} 

那么我也许可以写一个这样的程序:

public class Solution {
    public static void main(String[] args) {
        BuyAHouseInc jane = new BuyAHouseInc("jane", "doe", "123 main street", 100000);
        BuyAHouseInc john = new BuyAHouseInc("john", "doe", "123 main street", 50000);

        System.out.println("The following clients can afford to buy a house");

        if (canAffordTheHouse(jane)) {
            jane.displayClient();
        }
        if (canAffordTheHouse(john)) {
            john.displayClient();
        }
    }

    public static boolean canAffordTheHouse(BuyAHouseInc client) {
        return client.getBudget() > 50000;
    }
}

【讨论】:

    【解决方案2】:

    如果您询问的是 getter/setter 与直接访问,那么 getter/setter 与直接访问相比有很多优势。 基本上:

    1. 它更安全,因为变量实现应该保持私有 并且无法通过公共资源访问。
    2. 它允许在 get/set 调用和 允许为谁获取/设置不同的行为。
    3. 它允许不同的访问级别(公共、受保护等)
    4. 但是,它与直接访问的速度完全相同。

    这是另一个answer,它更详细地显示了我所说的内容。

    【讨论】:

    • 私有字段的封装使代码更容易推理,但不提供通常意义上的安全性。此外,方法的行为不是由调用者决定的(#2)。
    【解决方案3】:

    你可以组合代码块

    public class BuyAHouseInc
    {    
    
        // Instance variables
        private String firstName;
        private String surname;
        private String address;
        private int budget;
    
        public void displayClient()
        {
            System.out.println("Client Name: " + this.firstName + " " + this.surname);
            System.out.println("Address: " + this.address);
            System.out.println("Budget: " + "€" + this.budget);
        }
    
        // method to set the first name in the object
        public void setFirstName(String firstName)
        {
            this.firstName = firstName; // stores the first name
        }
    
        // method to retrieve the first name from the object
        public String getFirstName()
        {
            return firstName; // return value of first name to caller 
        }
    
        // method to set the surname in the object
        public void setSurname(String surname)
        {
            this.surname = surname; // stores the surname
        }
    
        // method to retrieve the surname from the object
        public String getSurname()
        {
            return surname; // return the value of surname to caller
        }
    
        // method to set the address in the object
        public void setAddress(String address)
        {
            this.address = address; // stores the address
        }
    
        // method to retrieve the address from the object
        public String getAddress()
        {
            return address; // return the value of address to caller
        }
    
        // method to set the budget in the object 
        public void setBudget(int budget) 
        {
            this.budget = budget; // store the budget
        }
    
        // method to retrieve the budget from the object
        public int getBudget()
        {
            return budget; // return the value of address to caller
        }
    
    }
    

    或者,您可以将BuyAHouseInc 的整个对象传递给显示函数。

    public void displayClient(BuyAHouseInc b)
    {
        System.out.println("Client Name: " + b.getFirstName()+ " " + b.getSurname());
        System.out.println("Address: " + b.getAddress());
        System.out.println("Budget: " + "€" + b.getBudget());
    }
    

    【讨论】:

    • displayClient看起来不像是一个toString方法吗?然后打印出方法。
    • @chrislovecnm - 确实如此,但我不想混淆 OP 的学习
    【解决方案4】:
    public void displayClient(String firstName, String surname, String address, int budget) 
    { 
    //........ 
    } 
    

    只是另一种方法。包含在{} 中定义了调用displayClient() 方法时的作用。 displayClient() 需要 3 个参数才能执行它的任务。参数是 public void displayClient(String firstName, String surname, String address, int budget) 中的 () 中的内容。第二段代码可以放在public class BuyAHouse 块或{ } 中。您的 setters()getters() 也类似于 displayClient(),但参数较少。

    public class BuyAHouse 的 { } 中的内容是成员或方法。这些方法可以访问类变量

        private String firstName;
        private String surname;
        private String address;
        private int budget;
    

    这就是为什么在setters() 的大多数语法中,您可以看到它是设置/分配/存储(无论您喜欢什么)值给您的类变量。所以基本上set()方法是用来修改变量firstname, surname,addressbudget的值

    getters() 用于返回变量的值。

    例如,

    String name; //this has no string value yet
    
    //function definition - you tell what you want this method to do
    public void setMyName(String yourName){
        name = yourName; //you store the value of yourName to name
    }
    
        //method call
        setMyName("whatever name you like"); // whatever name you like will be passed to the yourName variable
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      相关资源
      最近更新 更多