Ask Question
7 December, 10:08

Modify the following class so that the two instance variables are private and there is a getter method and a setter method for each instance variable:

public class Player {

String name;

int score;

}

+1
Answers (1)
  1. 7 December, 11:36
    0
    The program to this question can be given as follows:

    Program:

    class player//defining class player

    {

    //defining variable name and score.

    String name;

    int score;

    String get_Name () / /defining method get_Name

    {

    return name; / /return value.

    }

    void set_Name (String name) / /defining method set_Name

    {

    //using this keyword to hold variable value

    this. name = name; / /hold value

    }

    int get_Score () / /defining method get_Score

    {

    return score; / /return value

    }

    void set_Score (int score) / /defining method set_Score

    {

    //using this keyword to hold variable value

    this. score = score; / /return value

    }

    }

    public class Main / /defining class Main

    {

    public static void main (String[] args) / /defining main method

    {

    //defining variable

    int x;

    String n;

    player ob = new player (); / /creating player class Object

    ob. set_Name ("data"); / /calling function set_Name and pass the value.

    ob. set_Score (10); / /calling function set_Score and pass the value.

    n=ob. get_Name (); / /holding value

    x=ob. get_Score (); //holding value

    System. out. println (n+"/n"+x); / /print value.

    }

    }

    Output:

    data

    10

    Explanation:

    In the above java program, the class player is defined, which contains two-variable "name and score" in which the name is a string type and score is an integer type.

    In the next line, the getter and setter method is used, which is set is used to set the values and get is used to return the values. Then the Main class is declared inside the class the main method is defined that creates a player class object and call the function.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Modify the following class so that the two instance variables are private and there is a getter method and a setter method for each ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers