简体   繁体   English

返回对象引用在Java?

[英]Returning objects reference in java?

So i'm preparing for an exam and trying to figure this one out, whether it breaks encapsulation or not. 因此,我正在为考试做准备,并试图弄清楚这一点,无论它是否破坏封装。 No idea if with question even makes sense, but I'm working on a game that has a bunch of server classes and a client class Game. 不知道是否有问题还是有意义的,但是我正在开发一个具有大量服务器类和客户端类Game的游戏。 In my Player class I have this field 在我的玩家班级,我有这个领域

private Room currentRoom;

and a accessor method: 和访问器方法:

public void getCurrentRoom {
    return currentRoom;
}

Room class has: 房型有:

private String Name;
private ArrayList<Item> items;
private HashMap<String, Room> exists;

I've used the get method seven different places in the Game class, but I don't know if it breaks the principle of encapsulation by returning it directly - if it does, what would a better approach be? 我在Game类中使用了get方法的七个不同位置,但是我不知道它是否通过直接返回来破坏封装的原理-如果这样做,有什么更好的方法?

Thank you. 谢谢。

First off, this code won't compile, since it needs to return an instance of type Room 首先,该代码将无法编译,因为它需要返回Room类型的实例

public void getCurrentRoom {
    return currentRoom;
}

Does it break the principle of encapsulation? 是否违反了封装原理?

No. 没有。

Principle of Encapsulation: 封装原理:

Encapsulation helps to create code that is loosely coupled. 封装有助于创建松散耦合的代码。 Because the details are hidden, it reduces the ability of other objects to directly modify an object's state and behavior. 由于细节是隐藏的,因此降低了其他对象直接修改对象的状态和行为的能力。

  • Since your getter callers wouldn't know how the current room was set, it has hidden its implementation behind the scenes. 由于您的getter调用者不知道当前房间的设置方式,因此它隐藏了其实现。
  • Your function to set the current room needs to be private in order to hide the implementation 您需要设置当前房间的功能为private才能隐藏实现

Source: 资源:

https://gamedevelopment.tutsplus.com/tutorials/quick-tip-the-oop-principle-of-encapsulation--gamedev-2187 https://gamedevelopment.tutsplus.com/tutorials/quick-tip-the-oop-principle-of-encapsulation--gamedev-2187

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM