Java Public Var Question

Possible Duplicate:
Property and Encapsulation

NEWB Notice !!

I start with Android and Java, and I begin to understand this, but I wonder why I should use getters and setters, and not just public variables?

I see that many people make a private variable and create a get and set method.

What is the idea here?

+3
source share
5 answers

, - . , , .. . , - , . , .

, , , Long:

public class ContactInfo {
    private Long phoneNo;
    public Long getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(Long phoneNo) {
        this.phoneNo = phoneNo;
    }
}

getter/setter, /, PhoneNumber. ContactInfo :

public class ContactInfo {
    private PhoneNumber phoneNo;
    public Long getPhoneNo() {
        return phoneNo.getNumber();
    }
    public void setPhoneNo(Long phoneNo) {
        this.phoneNo = new PhoneNumber(phoneNo);
    }
}
public class PhoneNumber {
    private Long number;
    public PhoneNumber(Long number) {
        this.number = number;
    }
    public Long getNumber() {
        return number;
    }
}
+8

(google it). : () (accessors), , . , , . , , . , - .

+1

, " " http://en.wikipedia.org/wiki/Information_hiding

( ). , , , , . , .

, / . , String name, , , name = "". , public boolean setName(String newName), newName true false, .

0

.

, , - .

, , ,

public class Point{

  private   float x;
  private   float y;

  public float getX(){

     return x;
  }

  public float getY(){
    return y;
  }

  public float distanceToZero2(){

     return x*x + y*y
  }

  public float getAngle(){
    //havent considered the x = 0 case. 
    return atan(y/x);

   }

public boolean isInFirstQuad(){

   return x>0 && y>0;
}
}

, . , (, ).

Anyoune, , , / , Point .

0

, get . , age, >= 1

class Person {
   private int age = Integer.MIN_VALUE;

public void setAge(int age){
   if(age>=1)
      this.age = age;
}


public int getAge(){
   return age;
}
}
0

Source: https://habr.com/ru/post/1756677/


All Articles