JAVA home work write the code follow the steps below. 2Questions thank you so mu
ID: 3841669 • Letter: J
Question
JAVA home work write the code follow the steps below. 2Questions thank you so much!
(1)Write the class header and the instance data variables for the Cat class.
A cat is described by name, age, and whether or not the cat is an indoor-only cat.
Write a constructor for the Cat class that initializes a cat object by specifying all information.
Write accessor and mutator (getter and setter) methods. Include validity checking where appropriate.
Write a toString method to return a text representation of the cat that includes the name, age, and indoor status.
(2)Write code that would go inside a driver program with a main method.
Create an array to hold 6 Pet objects
Fill the array with some cats and some dogs.
Iterate the array and print a text representation of each pet.
Iterate the array and output the name of each outdoor cat.
Use polymorphism to do this!
Sort the array by invoking a Java-provided sorting method.
Explanation / Answer
Cat.java
public class Cat implements Comparable<Cat> {
private String name;
private int age;
private boolean indoorStatus;
public Cat(String name, int age, boolean indoorStatus) {
this.name = name;
this.age = age;
this.indoorStatus = indoorStatus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isIndoorStatus() {
return indoorStatus;
}
public void setIndoorStatus(boolean indoorStatus) {
this.indoorStatus = indoorStatus;
}
@Override
public String toString() {
return "Cat [name=" + name + ", age=" + age + ", indoorStatus=" + indoorStatus + "]";
}
@Override
public int compareTo(Cat o) {
return this.age - o.age;
}
}
TestCat.java
import java.util.Arrays;
public class TestCat {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat cats[]=new Cat[6];
cats[0]=new Cat("puppyCat",2,true);
cats[1]=new Cat("pussiCat",3,false);
cats[2]=new Cat("tommiCat",4,false);
cats[3]=new Cat("sonyCat",5,false);
cats[4]=new Cat("snupiCat",2,true);
cats[5]=new Cat("jurryCat",4,true);
Arrays.sort(cats);
for(Cat cat :cats)
{
if(!cat.isIndoorStatus())
System.out.println(cat);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.