|登录 |注册

查看: 2345|回复: 19
打印 上一主题 下一主题

关与java de get and set method。。(我基础不好)

[复制链接]
wo不帅
2011-7-13 12:25 AM
关与这两个method...
打出来我会,可是真正的用途我不知道。。
所以有时不知道几时才需要用这两个method...
Dhilip89
2011-7-13 09:12 AM
本帖最后由 Dhilip89 于 2011-7-13 09:13 AM 编辑
关与这两个method...
打出来我会,可是真正的用途我不知道。。
所以有时不知道几时才需要用这两个method. ...
wo不帅 发表于 2011-7-13 12:25 AM
  1. public class MyClass {
  2.     private int x;
  3.     public int y;

  4.     public MyClass() {
  5.     }

  6.     public int getX() {
  7.         return this.x;
  8.     }
  9.    
  10.     public void setX(int x) {
  11.         this.x = x;
  12.     }
  13. }
复制代码
  1. public class MyApp {
  2.     public static void main(String[] args) {
  3.         MyClass obj = new MyClass();

  4.         // 因为 obj.x 是 private 所以要用 get(accessor) / set(mutator)  
  5.         obj.setX(100);

  6.         // obj.y 是 public 所以可以直接调用
  7.         obj.y = 250;

  8.         System.out.println("obj.x = " + obj.getX());
  9.         System.out.println("obj.y = " + obj.y);
  10.     }
  11. }
复制代码
Super-Tomato
2011-7-13 02:17 PM
关与这两个method...
打出来我会,可是真正的用途我不知道。。
所以有时不知道几时才需要用这两个method. ...
wo不帅 发表于 2011-7-13 12:25 AM



private 属性不能直接被赋予值的時候就需要個 set method
但 get/set method 的好處是可以先用來做些所需的判斷,如判斷参數的值是不是為空等
宅男-兜着走
2011-7-13 11:16 PM
1. 能在你的get/set property 内判断 值, 假设你直接允许你的开发团去给属性赋予值 是不好的。
2. 维持个标准,
3. 同样的地方可能会派上用场, 代码复用。
~Zero
2011-7-14 10:07 AM
有些时候你要一些 parameter 只能 get,不能 set;或只能 set 不能 get。
wo不帅
2011-7-14 10:34 PM
謝謝你們的講解。。
我大概get到了。。
提示: 作者被禁止或删除 内容自动屏蔽
slay_alex92
2014-1-17 09:59 PM
本帖最后由 slay_alex92 于 2014-1-17 10:05 PM 编辑
shern91 发表于 2014-1-16 10:30 PM
this 是拿来做么?


this就是指你現在這個object哦
例如
  1. public class Test
  2. {
  3.         public int x;
  4.        
  5.         public Test(int x) //Constructor
  6.         {
  7.                 this.x = x; //外面第三行有x,但是這個constructor的argument也叫做x,所以你
  8.         }                 //在constructor裡面呼叫x,compiler會認為你在呼叫第5行的x(這個現象就叫shadow),
  9. }                       //如果你要在這個constructor裡面呼叫第三行的x,就要在前面加上this,
  10.                         //因為this是這個object instance的意思,而第三行的x是instance variable
复制代码
slay_alex92
2014-1-17 10:04 PM
是encapsulation的概念,java的instances variable最好都設成private,要用set/get的method來操作
這樣的程式安全性比較高,也比較容易維護
提示: 作者被禁止或删除 内容自动屏蔽
您需要登录后才可以回帖 登录 | 注册

JBTALKS.CC |联系我们 |隐私政策 |Share

GMT+8, 2026-1-1 06:54 AM , Processed in 0.087813 second(s), 25 queries .

Powered by Discuz! X2.5 © 2001-2012 Comsenz Inc.

本论坛言论纯属发表者个人意见,与本论坛立场无关
Copyright © 2003-2012 JBTALKS.CC All Rights Reserved

Dedicated Server powered by iCore Technology Sdn. Bhd.

合作联盟网站:
JBTALKS 马来西亚中文论坛 | JBTALKS我的空间 | ICORE TECHNOLOGY SDN. BHD.
回顶部