简体   繁体   English

getter / setter中的指定方法

[英]Specifying method in getter/setter

To actually understand the meaning of encapsulation, example that class private fields must be accessed through class public methods is as per definition, but actually stll it doesn't make difference as the field is still accessible as it is. 为了真正理解封装的含义,示例类私有字段必须通过类公共方法进行访问是按照定义的,但是实际上并没有什么区别,因为该字段仍然可以访问。
So,I think there should be some processing inside getters/setters to hide how the field is being handled. 因此,我认为在getters / setter方法内部应该进行一些处理,以隐藏字段的处理方式。 But it breaks the principal of behind pojos. 但这打破了背后的原则。 How can one handle this situation? 一个人如何处理这种情况?

I'm not sure what according to you is "the principle of POJOs". 我不确定您认为“ POJO的原理”是什么。 The following is a POJO and still hides implementation details behind getters and setters: 以下是POJO,仍然将实现细节隐藏在getter和setter后面:

public class Example {
    private int thousands;
    private int units;

    public void setValue(int value) {
        thousands = value / 1000;
        units = value % 1000;
    }

    public int getValue() {
        return 1000 * thousands + units;
    }
}

Encapsulation means not to expose the internals of your class. 封装意味着不公开您的类的内部。

In the Java context it means that the attributes of your class should NOT be accessible by other classes, instead your class should provide methods that will allow to access the attributes. 在Java上下文中,这意味着您的类的属性不应被其他类访问,而您的类应提供允许访问这些属性的方法。 In cases of POJO classes these methods will only allow to set ( setters ) and get ( getters ) the values of the attributes from the POJO class. 在POJO类的情况下,这些方法只允许从POJO类设置(setter方法 ),并获得( 吸气 )属性的值。

The goal of encapsulation is to protect the attributes of your class from being modified by other classes. 封装的目的是保护您的类的属性不被其他类修改。 Your class is obviously able to do whatever you want with the attributes inside your classes. 显然,您的班级可以利用班级内的属性来做任何您想做的事情。

No, the field is not accessible as it is. 不,该字段不能直接访问。 All it takes to make a method a getter or a setter ist the proper signature. 使方法成为获取器或设置器的正确签名所需要的全部工作。

public String getFoo() {
  return null;
}

This is a perfect getter for a String foo , even though it returns null . 即使它返回null ,这也是String foo的完美获取器。

public void setFoo(String foo) {
  // do nothing
}

This is a perfect setter for the same member, even though it does nothing. 即使不执行任何操作,这对于同一位成员也是一个完美的设置者。

One of the many uses of getters and setters is to restrict the value of the variable. getter和setter的许多用途之一是限制变量的值。 By making the data members private and keeping the getters and setters public, the programmer can keep a check on the value of the variable. 通过使数据成员成为私有成员并使getter和setters保持公共状态,程序员可以对变量的值进行检查。 For ex: 例如:

class Employee
{
    private int age;

    public int getAge()
    {
        return this.age;
    }

    public void setAge(int age)
    {
        if(age<18 || age>60)
            this.age = age;
        else
            System.out.println("The age of the employee should be between 18 and 60");
    }
}

In this case the age of the Employee can never be more less than 18 and more than 60. 在这种情况下,员工的年龄绝不能超过18岁且不超过60岁。

Don't know why people usually mix Data Encapsulation with Data hiding. 不知道为什么人们通常将数据封装与数据隐藏混合在一起。 Data encapsulation simply means grouping data together whereas data hiding is a way to store this data so others cannot know it's internal implementation. 数据封装只是意味着将数据分组在一起,而数据隐藏是一种存储此数据的方式,因此其他人无法知道其内部实现。

Lets say you have a class PersonalInfo in which you have fields like name,gender,age etc. As a programmer(which you are) you will provide user some way to enter these fields, save them in your PersonalInfo object using setter methods.IF user wish to see the information you simple call getters and display information. 假设您有一个PersonalInfo类,其中包含诸如名称,性别,年龄等字段。作为程序员,您将为用户提供一些输入这些字段的方法,并使用setter方法将其保存在PersonalInfo对象中。用户希望看到您简单调用获取器的信息并显示信息。 Your implementation as in you may store this variables in a map may varry. 您的实现可能会将此变量存储在映射中,因此可能有所不同。 So you can say 所以你可以说

public void setName(String name){
  SomeMap.add("name",name);
}

Note * you are the programmer and you will always know the implementatio *n. 注意* 您是程序员,您将永远了解实现 * n。 Keeping the fields private is to allow only your class methods to access your data. 将字段设为私有是为了仅允许您的类方法访问数据。

Imagine it this way. 试想一下。 User can create an object. 用户可以创建一个对象。 He may set all fields using getters and setters. 他可以使用getter和setter设置所有字段。 It may be your implementation to calculate age using DOB(Date of Birth) in which case you will not provide setter for age. 使用DOB(出生日期)来计算年龄可能是您的实现,在这种情况下,您将不会提供年龄的设定者。 In this case user cannot say myObj.age=23. 在这种情况下,用户无法说出myObj.age = 23。 This is purely your implementation .Hope this clears the confusion! 这纯粹是您的实现。希望这可以消除混乱!

It's still accessible but you see when you use it directly (public variable) you can change the value of variable without any restriction. 它仍然可以访问,但是您看到直接使用它(公共变量)时,可以无限制地更改变量的值。 The advantage of using such kind of private variables with setter and getter methods is that you can write code inside the setter method to check whether the value set is in the expected range or not. 将此类私有变量与setter和getter方法一起使用的优点是,您可以在setter方法内编写代码,以检查所设置的值是否在预期范围内。 Or you can even store the value in different form than the apparent view. 或者,您甚至可以用不同于外观的形式存储值。 For example you may store the value of a variable by adding offset to the value of the parameter of the setter method and in getter method you may just revert back the process(Encapsulation). 例如,您可以通过将偏移量添加到setter方法的参数值中来存储变量的值,而在getter方法中,您可以仅还原过程(封装)。 When the value set is not in the expected range you may even throw exceptions. 当设置的值不在预期范围内时,您甚至可能引发异常。

Example1: Here var1 is a private variable 例1:var1是一个私有变量

public void setValue(int var1){
         if(var1<0){
                //throw exception
          }
         this.var1=var1;
 }

Example2: 范例2:

 public void setValue(int var1){
        this.var1=calculatesomething+var1;
}
public int getValue(){
        return calculatesomething+this.var1;
}

That's the use of encapsulation.....all the best 那就是封装的用途。。。

Encapsulation is to restrict the access to the Class's variables and to regularize the way of editing them. 封装是为了限制对Class变量的访问,并规范化它们的编辑方式。

Class Test
{
 public int a;
 public Test()
 {
  a = 0;
 }
 public getA()
 {
  return a;
 }

 public setA(int a)
 {
   this.a = a
 }
}

Class TestMain
{
  main()
 {
   Test t = new Test();
   System.out.println(t.a);   // This prints 0;
   int a = t.getA();
   a = 10;
   System.out.println(t.a);   // This still prints 0;

   t.a = 20;
   System.out.println(t.a);   // This prints 20;
 }
}

In the above example the programmer may not be intentionally changing the value of ta but the value changes. 在上面的示例中,程序员可能没有故意更改ta的值,但该值更改了。

If he really intents to change it, then he should use the setter. 如果他真的有意更改它,那么他应该使用二传手。

Encapsulation is the feature that java provides which solves certain practical problems and helps in extensibility. 封装是java提供的功能,可以解决某些实际问题并有助于扩展。

If the Test and TestMain classes are written by same person, there wont't be any confusion. 如果Test和TestMain类是由同一个人编写的,则不会有任何混淆。 But practically that is not the case. 但实际上并非如此。

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

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