Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help on Java code. Please help me find the code for this Question. Thanks

ID: 3858339 • Letter: I

Question

I need help on Java code. Please help me find the code for this Question. Thanks!

Add a Dog class, with a Cat field called myCatFriend. Give Dog a constructor that takes a Cat object to populate its myCatFriend field. Add a “String thoughts” field to both the Cat and Dog classes. They can have default values, for example “None of your business” and “Play!”. Instantiate a Cat and a Dog in your main() routine. At this point make sure Eclipse does not display any errors. Finally, write a routine in the Dog class that includes the line.

Explanation / Answer

//Class Cat definition

class Cat

{

//Instance variable

String thoughts;

//Default constructor to initialize instance variable

Cat()

{

thoughts = "None of your business";

}//End of constructor

//Overrides toString() method

public String toString()

{

return thoughts;

}//End of method

}//End of class

//Class Dog definition

class Dog

{

//Instance variable

String thoughts;

//Cat class object

Cat myCatFriend;

//Default constructor to initialize instance variable

Dog()

{

thoughts = "Play!";

}//End of constructor

//Constructor takes Cat class object

Dog(Cat c)

{

myCatFriend = c;

}//End of constructor

//Overrides toString() method

public String toString()

{

return thoughts;

}//End of method

}//End of class

//Driver class

public class CatDogFriend

{

//Main method definition

public static void main(String ss[])

{

//Objects created

Cat cc = new Cat();

Dog dd = new Dog();

Dog dd1 = new Dog(cc);

//Displays Cat class information

System.out.println(cc);

//Displays Dog class information

System.out.println(dd);

//Displays Cat class information with the help of Dog class object

System.out.println(dd1.myCatFriend.thoughts);

}//End of main method

}//End of class

Output:

None of your business
Play!
None of your business

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote