Write a class called Person class. The Person class contains Two instance variab
ID: 3702667 • Letter: W
Question
Write a class called Person class. The Person class contains Two instance variable named name (of type String) and age (of type int) . A constructor that creates a Person instance with the given parameters. It must assign age after confirming the argument passed is not negative; if a negative argument is passed, the constructor should set age to 0 . Getters and setters for instance variables name and age . A toString() that returns a short description of the instance. A yearPasses() method that increases the age by 1 Write the Person class in the answer box below. Note - keep a copy of your solution to this task because you will be extending it step by step in subsequent tasks For example Test Result Person p- new Person(Joe 12)Joe (12) System.out.println(p);Explanation / Answer
ScreenShot
--------------------------------------------------------------------------------------------------------------------------------------
Program
//Person class
class person{
//Instance variables
String name;
int age;
//Constructor
person(String name,int age){
this.name=name;
//age is negative then set 0 else passed age
if(age<0) {
this.age=0;
}
else {
this.age=age;
}
}
//setter methods
public void setName(String name) {
this.name=name;
}
public void setAge(int age) {
this.age=age;
}
//Getter methods
public String getName() {
return name;
}
public int getAge() {
return age;
}
//toString method for printing result
public String toString() {
return name+"("+age+")";
}
//increment the age
public int yearPasses() {
age+=1;
return age;
}
}
//main class
public class PersonClass {
//Main method
public static void main(String[] args) {
//Object creation
person p=new person("Joe",12);
//output printing
System.out.println(p);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.