Java:访问器方法与受保护字段 [英] Java : Accessor methods vs protected fields

查看:124
本文介绍了Java:访问器方法与受保护字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道很多编码人员都使用访问器方法来访问某些类字段,这些类字段是其他类私有的,但是我想知道为什么.为什么他们不喜欢受保护的字段,而女巫只能从同一包的类而不是访问器访问?我的意思是,如果没有严重的原因,那只是代码浪费.

I know lots of coders use accessor methods to access some class fields which are private from other classes, but I was wondering why. And why they don't prefer protected fields witch are accessible only from classes of the same package instead of accessors? I mean if there is not a serious reason, it's just code waste.

推荐答案

仅定义访问字段的方法时,您会受到方法的限制.您无法做某事没有方法.

When you only define methods to access a field, you are restricted by the methods. You cannot do something that there is not a method for.

考虑此类:

public class Account {
    private int balance = 0;

    public int getBalance() {
        return balance;
    }

    public void insert(int amount) {
        if(amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(int amount) {
        if(amount > 0 && amount =< balance) {
            balance -= amount;
        }
    }
}

您可以通过插入和提取来更改帐户的余额,也可以检查它是什么.但是,如果您可以直接使用余额,则可以执行一些不可能的事情:

You can change the balance of the account by inserting and withdrawing, and you can check what it is. But if you had access to the balance directly, you could do something that is not supposed to be possible like:

Account acc = new Account();
acc.balance = -10;

此外,受保护实际上更接近于公共而非私有.如果您有一个私人领域,它将永远是私人的.如果您的字段受到保护,那么任何人都可以随时扩展您的课程并访问该字段.如果打算将其设为私有,并且将其设置为受保护,则当有人对其进行扩展时,它可能会失去其目的(并且他扩展的事实已不再有意义,因为他的新阶级并不以超阶级的精神行事).

Furthermore, protected is actually closer to public than to private. If you have a private field, it will be private forever. If your field is protected, anyone can always extend your class and access the field. If it is intended to be private and you set it to protected, it might lose its purpose when someone extends it (and the fact that he extended no longer makes sense, because his new class does not behave in the spirit of the superclass).

这篇关于Java:访问器方法与受保护字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆