Print person1's kids, call the incNumKids() method, and print again, outputting text as below. End each line with a newline.
Sample output for below program with input 3:

Kids: 3
New baby, kids now: 4
// ===== Code from file PersonInfo.java =====
public class PersonInfo {
private int numKids;

public void setNumKids(int setPersonsKids) {
numKids = setPersonsKids;
}

public void incNumKids() {
numKids = numKids + 1;
}

public int getNumKids() {
return numKids;
}
}
// ===== end =====

// ===== Code from file CallPersonInfo.java =====
import java.util.Scanner;

public class CallPersonInfo {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
PersonInfo person1 = new PersonInfo();
int personsKid;

personsKid = scnr.nextInt();

person1.setNumKids(personsKid);

/* Your solution goes here */

}
}
// ===== end =====

Respuesta :

Answer:

Hi there! This is a good question to grasp the concepts of object-oriented classes, encapsulation and abstraction of classes and their properties in Java. Please find the details below.

Explanation:

You can implement the solution by calling the getNumKids() function of the personInfo object or directly using the personKid input from the user to display the initial number of kids for the user. Then, calling the incNumKids() increases the kids count. Finally, displaying the new number of kids is done by invoking the getNumKids() method of the PersonInfo object that returns the private property of numKids to the user. The user cannot access this property without the get and set methods.

CallPersonInfo.java =====

import java.util.Scanner;

public class CallPersonInfo {

public static void main (String [] args) {

Scanner scnr = new Scanner(System.in);

PersonInfo person1 = new PersonInfo();

int personsKid;

personsKid = scnr.nextInt();

person1.setNumKids(personsKid);

System.out.println("Kids: " + personKid); // or person1.getNumKids();

   person1.incNumKids();

   System.out.println("New baby, kids now: " + personInfoObject.getNumKids());

 

}

}

You can also write the code in the same file as PersonInfo.java as below.

import java.util.Scanner;

class PersonInfo {

 private int numKids;

 public void setNumKids(int setPersonsKids) {

   numKids = setPersonsKids;

 }

 public void incNumKids() {

   numKids = numKids + 1;

 }

 public int getNumKids() {

   return numKids;

 }

 public static void main(String args[]) {

   System.out.println("Enter number of kids: ");

   Scanner scan = new Scanner(System.in);

   int num_kids = scan.nextInt();

   PersonInfo personInfoObject = new PersonInfo();

   personInfoObject.setNumKids(num_kids);

   System.out.println("Kids: " + num_kids);

   personInfoObject.incNumKids();

   System.out.println("New baby, kids now: " + personInfoObject.getNumKids());

 }

}