java访问器,Java中的访问器方法

本文探讨了在面向对象编程中使用private变量和setter/getter方法的封装概念。通过设置变量为private并使用getter和setter,可以确保对对象内部状态的控制,比如进行输入验证。例如,在设置狗的年龄时,通过setter方法可以防止输入负数,从而提高代码的健壮性。这种做法有助于维持数据完整性,并遵循良好的编程实践。
摘要由CSDN通过智能技术生成

So I have a question on "setter" and "getter" methods and how useful they are or aren't.

Let's say I just write a very basic program like the following:

public class Account

{

String name;

String address;

double balance;

}

Then, let's say I write another class that uses this "Account" class, like the following:

class UseAccount

{

public static void main(String[] args)

{

Account myAccount = new Account();

Account yourAccount = new Account();

myAccount.name = "Blah blah"

}

}

etc., etc.

When I write myAccount.name = "Blah blah", I am changing the value of the variable "name" in the "Account" class. I am free to do this as many times as I like with the code written the way it is. It has come to my attention, however, that it's better practice to make the variables in the "Account" class private, and then use "setter" and "getter" methods. So if I write the following:

public class Account

{

private String name;

private String address;

private String balance;

public void setName(String n)

{

name = n;

}

public String getName()

{

return name;

}

}

I can still change the value of the variable "name" by just creating another class that has something like:

class UseAccount

{

public static void main(String[] args)

{

Account myAccount = new Account();

myAccount.setName("Blah blah");

}

}

I don't understand how using this method is any different or is supposed to prevent people form changing the value of a private field. Any help?

解决方案

Try this Golden Rule of Object Oriented Programming.

1. Create private Instance variables.

2. Create public getters and setters to access those Instance variable.

3. This methodology is called Encapsulation. Though Encapsulation can be used in a different

way, that has importance in Design Patterns, Like Those Behaviors which keeps changing must

be encapsulated in an Abstract Class or Interfaces.

4. Well now back to the topic of Getter and Setter....

Getter and Setter helps Validating the Input to the Instance Variable.

For eg:

Assume i got a method to assign the Age of the Dog, Now the age can NoT be negative, If i dont have setter method, then i will not be able to Validate the Input of age.

private int age;

public void setDogAge(int age){

if (age>0){

this.age = age;

}

else{

System.out.println("Please Enter a Valid Age");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值