Java setters and getters

后端 未结 7 1655
情书的邮戳
情书的邮戳 2020-12-06 22:42

I have been struggling with setters and getters in java for quite a long time now.

For instance, if I want to write a class with some information as name, sex, age

7条回答
  •  清歌不尽
    2020-12-06 23:15

    You need to create an object of one class in the other class. You can then call the .get() and .set() methods on them. I will post an example in 2 minutes

    First class (i'll call it Person) will have methods to return its fields

    private String name = "";
    private String age = 0;
    
    public Person(String name, int age) {
      this.name = name;
      this.age = age;
    }
    
    public String getName() {
      return name;
    }
    
    public int getAge() {
      return age;
    }
    

    The second class will call those methods after it creates an object of the first class

    bob = new Person("Bob", 21);
    System.out.println("Your name is: " +  bob.getName() + 
                        " and you are " +  bob.getAge());
    

提交回复
热议问题