面向物件三大特征:封裝、繼承、多型,
封裝裝性在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));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/299263.html
標籤:其他
下一篇:設計模式---中介者模式
