面向对象三大特征:封装、继承、多态。
封装装性在Java当中的体现:
- 方法就是一种封装
- 关键字private也是一种封装
封装就是将一些细节信息隐藏起来,对于外界不可见。
—旦使用了private进行修饰,那么本类当中仍然可以随意访问。但是!超出了本类范围之外就不能再直接访问了。
间接访问private成员变量,就是定义一对儿Getter/Setter方法
必须叫setXxx或者是getXxx命名规则。
- 对于Getter来说,不能有参数,返回值类型和成员变量对应;
- 对于setter来说,不能有返回值,参数类型和成员变量对应。
public class work2 {
private int x;
private int y;
public void setX(int x) {
if (x > 0)
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
if (y > 0)
this.y = y;
}
public int getY() {
return y;
}
public String toString() {
return "(" + x + "," + y + ")";
}
public boolean equals(work2 date){
if(date.getX()==this.getX()&&date.getY()==this.getY()){
return true;
}
return false;
}
}
public class work2_1 {
public static void main(String[] args) {
work2 date = new work2();
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
date.setX(x);
date.setY(y);
work2 date2 = new work2();
date2.setY(x);
date2.setX(y);
System.out.println(date==date2);
System.out.println(date2.equals(date));
}
}