Question
public class Yorkie { private String name; private int age; public Yorkie(String name, int age) { this .name = name; this .age = age; }
public class Yorkie {
private String name;
private int age;
public Yorkie(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
String temp = "Yorkie Data ";
temp += "Name: " + name + " ";
temp += "Age: " + age + " ";
return temp;
}
}
public class Husky {
private String name;
private int age;
public Husky(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
String temp = "Husky Data ";
temp += "Name: " + name + " ";
temp += "Age: " + age + " ";
return temp;
}
}
these classes are very similar. In fact, this would be a perfect time to utilize inheritance in order to achieve some code reuse. This is the goal of this lab. Well create a superclass, called Dog, from which both of these classes will inherit.
First, lets create the superclass, Dog. Create a new project. Then, create a new class, Dog.
Leave the main method there for now. Well use it to test our classes later on. For now, we need to begin by declaring some data fields. Looking at the Husky/Yorkie classes, we can see theyll have two fields in common: name and age. Well keep these as private in order to keep a proper encapsulation from other classes.
Next, lets tackle the constructor. We simply want one to set the two fields accordingly. Note that well actually make this public; however, as well see later, the protected modifier would be better. Well also use the this reference here to distinguish between local parameter and data field.
Up next, we must write out a toString method as it would also be useful seeing that both the subclasses would use it in some way.
That should do it for the Dog class for now. We have taken care of all of the shared content between the original Husky/Yorkie classes. Now, lets rewrite the Husky class. We can now get rid of the data fields as well have access through the constructor of the Dog class. In rewriting the constructor, well simply use the superclass constructor to set both of the fields. Finally, the toString will call the superclass toString in order to build the String.
See how much less there is in this class? Now, since this was a small example, this may not seem to matter too much; however, this code reuse builds up over time. Now, do the same for the Yorkie class.
Now, in order to test this, lets go to the main method of the Dog class.
In testing this, youll see that both types of dog print out properly.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started