Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Challenge: Updating User Information | Classes Advanced
Java Extended

book
Challenge: Updating User Information

Compito

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.

  1. Implement the getName() and getAge() methods, as well as the setName() and setAge() methods with the appropriate parameters and types.

  2. Update the name and age using the setName() and setAge() methods.

  3. Print the object with the updated fields to the console.

Soluzione

java

solution

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());
}

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 6
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: " + ___);
}
toggle bottom row
We use cookies to make your experience better!
some-alt