56.4k views
2 votes
String is an example of an immutable class. The Person class that is started below, is not. Add the method haveBirthday that will increase the person’s age and the getter and setter method for the name variable. public class Person{ private String myName; private int myAge; public Person(String name, int age){ myName = name; myAge = age; } public void printMe(){ System.out.println("Name: " + myName + "\tAge: " + myAge); }

1 Answer

4 votes

Answer:

import static java.lang.System.out;

class Person

{

private String myName;

private int myAge;

String getName() //getter for myName

{

return myName;

}

void setName(String name) //setter for myName

{

myName=name;

}

public Person(String name, int age)

{

myName = name;

myAge = age;

}

public void printMe()

{

System.out.println("Name: " + myName + "\tAge: " + myAge);

}

public int haveBirthday() //Age is incremented

{

return myAge+=1;

}

}

public class Abc

{

public static void main (String args[])

{

Person p=new Person("rajpal",22); //object for class is created

System.out.println(p.getName()+" age after birthday is "+p.haveBirthday());

}

}

Step-by-step explanation:

Method for age increment i.e. haveBirthday() is created and a new main class is creted which is callinh haveBirthday() method.

User Jocassid
by
5.5k points