操作其他类中的私有对象

问题描述 投票:0回答:1

我正在处理这两个课程:

public class Journey
{
    private int journeyID;                 // the id of the journey
    private String transportMode;          // the public transport mode of the journey (can be only “train”, “bus” or “tram”) 
    private int startOfJourney;            // the starting point of the journey. It can be only a number between [1..10] 
    private int endOfJourney;              // the ending point of the journey. It can be only a number between [1..10] (should be different from the starting point of the journey)
    private int distanceOfJourney; 
public class SmartCard
{
    private int cardID;           // the id of the smartcard
    private char type;            // the type of the smartcard (it can be "C", "A" or "S")
    private float balance;       // the balance available on the smartcard (should have a minimum balance of $5)
    private Journey journey1 = null;             // journey object
    private Journey journey2 = null;             // journey object - can only be used if the type of the smartcard is "A" or "S"
    private Journey journey3 = null;

我需要编写一种方法,将新旅程添加到现有智能卡之一。但是,我无法弄清楚如何在不将其更改为公共的情况下访问journey1对象。我不允许在此任务中使用 ArrayList,因此我可以对如何操作类中的对象有任何建议吗?谢谢你。

我尝试使用

访问 Journey 对象
smartCard1.journey1 == null;

但它声明我无法访问私有对象。相反,我尝试创建一个 getJourneyID() 方法并使用

smartCard1.journey1.getJourneyID()==0;

但这也行不通。

java
1个回答
0
投票

请参阅维基百科上的Mutator Method。也称为 getter/setter 方法。

您可以将成员字段保持私有,但通过

get…
/
set…
方法提供读取和/或写入访问权限。

© www.soinside.com 2019 - 2024. All rights reserved.