Challenge: Updating User Information
Uppgift
Swipe to start coding
Your task is to update the fields of the existing person
object using setters and getters. Change the name to Bob
and set the age to 27
.
-
Implement the
getName()
andgetAge()
methods, as well as thesetName()
andsetAge()
methods with the appropriate parameters and types. -
Update the name and age using the
setName()
andsetAge()
methods. -
Print the object with the updated fields to the console.
Lösning
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice");
person.setAge(30);
System.out.println("Initial Person's name: " + person.getName() + ", Initial Person's age: " + person.getAge());
person.setName("Bob");
person.setAge(27);
System.out.println("Updated Person's name: " + person.getName() + ", Updated Person's age: " + person.getAge());
}
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 5. Kapitel 6
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.example;
class Person {
private String name;
private int age;
public ___ getName() {
return ___;
}
public ___ setName(String name) {
this.name = ___;
}
public ___ getAge() {
return ___;
}
public ___ setAge(int age) {
this.age = ___;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice");
person.setAge(30);
System.out.println("Initial Person's name: " + person.getName() + ", Initial Person's age: " + person.getAge());
___.setName(___);
___.setAge(___);
System.out.println("Updated Person's name: " + ___ + ", Updated Person's age: " + ___);
}
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal