【问题标题】:Exercise 115; should I use getters/setters or something else?练习 115;我应该使用 getter/setter 还是其他东西?
【发布时间】:2014-02-10 08:21:22
【问题描述】:

我完成了练习 105。但我不知道如何处理 115。我已经工作了一点点并且进步了一点点,但这是练习:

一个生物学家团队正在进行一项实验,该实验涉及收集在 1 平方公里的林地中发现的动物的数据。识别出每只动物后,都会记录其名称、发现时间以及发现它的科学家的姓名首字母。数据将记录在笔记本电脑上。设计和实现一个系统来存储数据,并彻底测试你的代码。

[提示:考虑为每个发现创建一个对象。每个对象应该存储什么信息,这些对象将存储在什么位置?]

这是我的代码:

// put class definitions here



public class Record{

    String name;

    String initials;

    String time;



    public Record{

        this.name = name;

        this.initials = initials;

        this.time = time;

    }

}

这是我测试解决方案的另一部分:

public static void main( String[] args )

{

  // test your solution here



}

所以我知道我应该从变量中创建一个新对象,但是我需要使用 getter 和 setter 吗?如果是这样的话,它可能会比我想象的要容易得多。

谢谢

【问题讨论】:

    标签: class object setter getter public-method


    【解决方案1】:

    Getter 和 setter 是从 Objects 获取内部成员变量的常用模式。它们不是强制性的,但这是一种很好的做法。

    您需要阅读一些 Java 和面向对象的书籍才能理解我们为什么要这样使用它。您需要了解为什么也鼓励封装。

    public class Record{
    
        protected String name;
    
        protected String initials;
    
        protected String time;
    
    
    
        public Record{
    
            this.name = name;
    
            this.initials = initials;
    
            this.time = time;
    
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        //... etc.
    }
    

    【讨论】:

    • 谢谢。我仍然没有完美的答案,但我会向您展示一些改进的代码。它仍然不完美,我不知道在我的子类中将我的数组列表、getter 或 setter 放在哪里......
    猜你喜欢
    • 2017-05-22
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2017-10-09
    • 2011-11-04
    • 1970-01-01
    • 2011-04-03
    • 2011-02-02
    相关资源
    最近更新 更多