222k views
5 votes
EX 4.11 Suppose you have a class called Child with an instance data value called age. Write a getter method and a setter method for age.

User Well
by
8.0k points

2 Answers

3 votes

Answer:

public int getAge(){

return this.age;

}

public void setAge(int age){

this.age = age;

}

Step-by-step explanation:

The above code snippet has been written in Java.

The given instance variable, age, is of type int which stands for integer.

Getter method

The getter method will return the instance variable in question. In naming a getter method, the convention is to write 'get' followed by the name of the instance variable, which is 'age' in this case as follows:

getAge()

getAge() has no parameter and it has a return type of int which denotes the data type of the instance variable in question, age in this case. The complete method declaration for getAge which returns the instance variable, age, is written as follows:

public int getAge(){

return this.age;

}

Setter method

The setter method will assign a value to the instance variable in question. In naming a setter method, the convention is to write 'set' followed by the name of the instance variable, which is 'age' in this case as follows:

setAge()

setAge() has one parameter of type int, which is the value to be assigned to the instance variable age, and it has a return type of void which shows that method need not return a value. The complete method declaration for setAge which assigns a value to the instance variable, age, is written as follows:

public void setAge(int age){

this.age = age;

}

PS: Complete code including the class

public class Child{

int age; // instance variable age

public int getAge(){ // getter method for age

return this.age;

}

public void setAge(int age){ // setter method for age

this.age = age;

}

}

Hope this helps!

User Huzoor Bux
by
8.2k points
7 votes
public void setAge(int new_Age) {
age = new_Age;
}

public int getAge(){
return age;
}
User Abraham Zinala
by
8.8k points