ITSC 1213 - Inheritance Part 1 Concepts covered in this lab: Implementing a superclass Implementing subclasses...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
ITSC 1213 - Inheritance Part 1 Concepts covered in this lab: Implementing a superclass Implementing subclasses Introduction Inheritance is a relationship between a more general class (called the superclass) and a more specialized class (called the subclass). The subclass inherits features and behavior from the superclass. For example, consider the relationships between different people on a campus as depicted in the figure below. Every student is a person. Students share the common properties of all persons, such as name, id, etc. We say that the Student class inherits from the Person class. Similarly, a professor is a person. We use an open arrow pointing to the superclass to represent the inheritance relationship in the UML diagram. Student Person Page < Professor 1 Part A At the top of this inheritance hierarchy, we have the superclass Person. A person has a name and id and can display personal information. In this part, we are going to implement the Person class. 1. Create a new project in NetBeans called InheritanceLab. Make sure to check the "Create Main Class" box to create the main Java class for this project. of 8 ZOOM + 2. Add a new Java class to the project called Person. The UML class diagram for Person is as follows: Person - firstName: String - lastName: String - id: int + Person(String, String, int) + getFirstName(): String + getLastName(): String + getId(): int + display(): void Page < 2 3. Start adding the instance variable definitions to your Person class. Make sure you add your code after the class definition line ( public class Person{ ). 4. The UML diagram also indicates that we need to add constructors and getters for the fields. Add those after the field definitions. of 8 ZOOM + 5. Add the display () method. This method should print out the full name and Id of a Person object. 6. Let's test to make sure the Person class works. In the main class of your project add code to create a Person object and call the display () method to print the object's detail, like this: Q D } /** * @param args the command line arguments */ PAADS public static void main(String[] args) { // TODO code application logic here System.out.println("*** Part A ***"); Person p = new Person ("Raya", "Whitaker", 800555555); p.display(); } Page < 2 7. You should now be able to run this project, and see an output similar to this: Output x run: *** Part A *** Name: Raya Whitaker ID: 800555555 BUILD SUCCESSFUL (total time: 0 seconds) Run your project and fix any bugs you encounter. of 8 ZOOM + 8. When your program works you will have created a Person class. In the next part, we'll subclass this to create other classes. Show your work to the instructional team to get checked off and proceed to Part B. Part B In Part A, we implemented the Person class, which only stores basic personal information. In this part, you will implement a more specific subclass and see how it inherits functionality from its superclass. 1. Add a new Java class to the project called Student. Since a student is a specific type of person we want this class to have the same fields and methods as the Person class. We can redo everything we just did in Part A but it is better to use inheritance and make Student a subclass of the Person class. This way, you can utilize everything you have done in part A. 2. To make the Student class a subclass of Person Class, simply add "extends Person" to the class header of the Student class. It should look like this: public Student extends Person { } Page < 3 Once you do this, you will notice that there is an error notification beside the class declaration. If you hover over it, it tells you something about no suitable constructor being found for Person. We will fix this error soon. 8 9 10 public class Student extends Person ( } constructor Person in class Person cannot be applied to given types; required: String,int found: no arguments reason: actual and formal argument lists differ in length (Alt-Enter shows hints) of 8 ZOOM + 3. The UML class diagram for Student class is as below: - major: String - gpa: double - credits: int - balance: double Student - transfer: boolean - enrolledCourses: ArrayList + Student(String, String, int, String, double, int) + getMajor(): String + getGPA(): double + getCredits(): int + is Transfer(): boolean + getBalance(): double + getEnrolledCourses(): ArrayList + setMajor(String): void + setGPA(double): void + setCredits(int): void + setTransfer(boolean): void + setBalance(double): void + addCourse(String): void + dropCourse(String): boolean Page < 4 of 8 ZOOM + Page < 4 As you can see, the Student class does not include the fields or methods that you defined in the Person class. This is because with inheritance, all of the public members of the superclass are automatically inherited by the subclass. Therefore, a Student object will be able to use the getFirstName (), getLastName (), getId() and display() methods. On the other hand, the private fields of the Person class cannot be accessed directly in the Student class. This is because private members are only accessible within the class that they belong to. Fortunately, we can still access them through the public getters defined in Person class. Actually, when a Student object is created, the object has a firstName, lastName and an id in memory but they are only accessible through any getters and setters methods we include. If you would like to access private fields of a parent class directly in a subclass you can choose to make those fields protected instead of private. 4. Add fields to the Student class. Don't forget to create/initialize the ArrayList. 5. Now we are going to fix the error related to the constructor. Let's first think about it. If we consider the process of constructing a subclass object we would realize that we need to initialize fields of both the superclass and the subclass. As a result, Java requires a subclass constructor to call the superclass constructor as the first job. This can be done implicitly if the superclass has a default constructor. However, there is no default constructor in the Person class, so we must call the non-default constructor explicitly. Th of 8 ZOOM + Page < constructor in the Person class, so we must call the non-default constructor explicitly. This is why there is the compiler error that you saw earlier. 6. To be able to initialize the fields defined in the Person class, the constructor of the Student class includes 6 parameters, three of which will be used to initialize the fields in the Person class. Add the header of the constructor in your Student class. 7. Now complete the constructor by adding statements to initialize all the fields including the ones defined in the Person class. Remember that the first statement in the constructor of any subclass must be the call to the constructor of the superclass. You can do this by using the keyword super() and since we want to initialize all the fields the Student class, including the ones defined in the Person class, we can use the second constructor: super (firstName, lastName, id) This calls the constructor of the superclass and initializes those fields with the parameters passed into the Student constructor. Don't forget to create/initialize the ArrayList. Your complete constructor might look like this: public Student (String fName, String lName, int id, String major, double gpa, int credits) { } super (fName, lName, id); major; 5 this.major this.gpa = gpa; this.credits = credits; = balance = 0; enrolledCourses = new ArrayList(); > 8. In Student.java, add the setters and getters you see listed in the UML class diagram. Remember that setters and getters are related to encapsulation. Refer to Unit 5 in the CS Awesome textbook for a refresher on encapsulation. 9. Next add the addCourse () and dropCourse () methods. Note that these methods are specific to the Student class. You can only apply them to Student objects, not Person objects. The addCourse () method adds the provided course to the ArrayList of courses for this student. The dropCourse () method removes the course from this list. If there is a course in the list that matches the course provided, remove the course from the list and return true. If there isn't a course in the list that matches, return false. of 8 ZOOM + Page < 8. In Student.java, add the setters and getters you see listed in the UML class diagram. Remember that setters and getters are related to encapsulation. Refer to Unit 5 in the CS Awesome textbook for a refresher on encapsulation. 5 9. Next add the addCourse () and dropCourse () methods. Note that these methods are specific to the Student class. You can only apply them to Student objects, not Person objects. The addCourse () method adds the provided course to the ArrayList of courses for this student. The dropCourse () method removes the course from this list. If there is a course in the list that matches the course provided, remove the course from the list and return true. If there isn't a course in the list that matches, return false. Think back to our ArrayList lab where we created methods just like these to update our ArrayList. 10. Let's test to make sure our subclass works. In the main method of your main class file, and add statements to create a Student object and test the different methods, like this: Student s1 = new Student("Xavier", "Cato", 900111222, "CS", 3.5, 75); s1.setTransfer(true); s1.setBalance (100); s1.addCourse ("Java Programming"); s1.addCourse ("Calculus"); s1.display(); if (s1.dropCourse ("Spanish")) { System out println("The class has been dropped") of 8 ZOOM + s1.setBalance (100); s1.addCourse ("Java Programming"); s1.addCourse("Calculus"); Student s1 = new Student ("Xavier", "Cato", 900111222, "CS", 3.5, 75); s1.setTransfer(true); s1.display(); if (s1.dropCourse ("Spanish")) { System.out.println("The class has been dropped"); } else { } System.out.println("You are not enrolled in this course. + "No courses have been dropped."); } 11. Run your project, and you should see an output similar to this: Output - 1213 Module6 (run) X DD run: DD on 54 Page < ArrayList enrolled Courses = s1.getEnrolledCourses(); System.out.println("You are enrolled in the following courses:"); for (String course : enrolled Courses) { System.out.println(course); *** Part A *** || Calculus BUILD SUCCESSFUL (total time: 0 seconds) 6 Name: Raya Whitaker ID: 800555555 *** Part B *** Name: Xavier Cato ID: 900111222 You are not enrolled in this course. No courses have been dropped. You are enrolled in the following courses: Java Programming 12. When your program works and you are satisfied with the result, show your work to the instructional team to get checked off and proceed to Part C. of 8 ZOOM + Part C 1. Follow the same procedure we followed in Part B to add the Professor class. The UML class diagram is as follows: Professor - department: String - salary: double - advisees: ArrayList + Professor(String, String, int, String, double) + getDepartment(): String + getSalary(): double + getAdvisees(): ArrayList + setDepartment(String): void + setSalary(double): void } + addAdvisee(Student): void + removeAdvisee(int): boolean 2. To test your Professor class add the following statement to the main method in the main class prof1.addAdvisee(s2); prof1.addAdvisee(s3); prof1.addAdvisee (s4); prof1.display(); Page < 7 System.out.println("*** Part C ***"' ) ; Student s2 = new Student ("Kathrine", "Johnson", 900, "CS", 4.0, 100); Student s3 = new Student ("Roy", "Clay", 901, "Biology", 3.2, 85); Student s4 = new Student("Kimberly", "Bryant", 902, "EE", 3.0, 80); Professor prof1 = new Professor("Mary", "Castro", 300, "CS", 80000); if (prof1.removeAdvisee (902)) { System.out.println("The advisee has been removed"); } else { System.out.println("This student is not an advisee of Professor + profl.getFirstName() + " " + profl.getLastName()); of 8 ZOOM + Page < ArrayList myAdvisees = prof1.getAdvisees(); System.out.println("Professor " + prof1.getFirstName() + + prof1.getLastName() + advisees:"); for (Student s: myAdvisees) { || 11 System.out.println(s.getFirstName() + + s.getLastName()); } 3. Run your project and fix any bugs you encounter. your output might look like this: *** Part C *** Name: Mary Castro ID: 300 The advisee has been removed Professor Mary Castro advisees: Kathrine Johnson Roy Clay BUILD SUCCESSFUL (total time: 0 seconds) 4. When your program works and you are satisfied with the result, show your work to the instructional team to get checked off for this lab. of 8 ZOOM + Bonus Add and generate JavaDoc for this project Page < So what did you learn in this lab? 1. How to extend a superclass 2. How to create appropriate constructor(s) in a subclass 3. How to use super to call methods in the superclass that have been overridden in the subclass of 8 ZOOM + ITSC 1213 - Inheritance Part 1 Concepts covered in this lab: Implementing a superclass Implementing subclasses Introduction Inheritance is a relationship between a more general class (called the superclass) and a more specialized class (called the subclass). The subclass inherits features and behavior from the superclass. For example, consider the relationships between different people on a campus as depicted in the figure below. Every student is a person. Students share the common properties of all persons, such as name, id, etc. We say that the Student class inherits from the Person class. Similarly, a professor is a person. We use an open arrow pointing to the superclass to represent the inheritance relationship in the UML diagram. Student Person Page < Professor 1 Part A At the top of this inheritance hierarchy, we have the superclass Person. A person has a name and id and can display personal information. In this part, we are going to implement the Person class. 1. Create a new project in NetBeans called InheritanceLab. Make sure to check the "Create Main Class" box to create the main Java class for this project. of 8 ZOOM + 2. Add a new Java class to the project called Person. The UML class diagram for Person is as follows: Person - firstName: String - lastName: String - id: int + Person(String, String, int) + getFirstName(): String + getLastName(): String + getId(): int + display(): void Page < 2 3. Start adding the instance variable definitions to your Person class. Make sure you add your code after the class definition line ( public class Person{ ). 4. The UML diagram also indicates that we need to add constructors and getters for the fields. Add those after the field definitions. of 8 ZOOM + 5. Add the display () method. This method should print out the full name and Id of a Person object. 6. Let's test to make sure the Person class works. In the main class of your project add code to create a Person object and call the display () method to print the object's detail, like this: Q D } /** * @param args the command line arguments */ PAADS public static void main(String[] args) { // TODO code application logic here System.out.println("*** Part A ***"); Person p = new Person ("Raya", "Whitaker", 800555555); p.display(); } Page < 2 7. You should now be able to run this project, and see an output similar to this: Output x run: *** Part A *** Name: Raya Whitaker ID: 800555555 BUILD SUCCESSFUL (total time: 0 seconds) Run your project and fix any bugs you encounter. of 8 ZOOM + 8. When your program works you will have created a Person class. In the next part, we'll subclass this to create other classes. Show your work to the instructional team to get checked off and proceed to Part B. Part B In Part A, we implemented the Person class, which only stores basic personal information. In this part, you will implement a more specific subclass and see how it inherits functionality from its superclass. 1. Add a new Java class to the project called Student. Since a student is a specific type of person we want this class to have the same fields and methods as the Person class. We can redo everything we just did in Part A but it is better to use inheritance and make Student a subclass of the Person class. This way, you can utilize everything you have done in part A. 2. To make the Student class a subclass of Person Class, simply add "extends Person" to the class header of the Student class. It should look like this: public Student extends Person { } Page < 3 Once you do this, you will notice that there is an error notification beside the class declaration. If you hover over it, it tells you something about no suitable constructor being found for Person. We will fix this error soon. 8 9 10 public class Student extends Person ( } constructor Person in class Person cannot be applied to given types; required: String,int found: no arguments reason: actual and formal argument lists differ in length (Alt-Enter shows hints) of 8 ZOOM + 3. The UML class diagram for Student class is as below: - major: String - gpa: double - credits: int - balance: double Student - transfer: boolean - enrolledCourses: ArrayList + Student(String, String, int, String, double, int) + getMajor(): String + getGPA(): double + getCredits(): int + is Transfer(): boolean + getBalance(): double + getEnrolledCourses(): ArrayList + setMajor(String): void + setGPA(double): void + setCredits(int): void + setTransfer(boolean): void + setBalance(double): void + addCourse(String): void + dropCourse(String): boolean Page < 4 of 8 ZOOM + Page < 4 As you can see, the Student class does not include the fields or methods that you defined in the Person class. This is because with inheritance, all of the public members of the superclass are automatically inherited by the subclass. Therefore, a Student object will be able to use the getFirstName (), getLastName (), getId() and display() methods. On the other hand, the private fields of the Person class cannot be accessed directly in the Student class. This is because private members are only accessible within the class that they belong to. Fortunately, we can still access them through the public getters defined in Person class. Actually, when a Student object is created, the object has a firstName, lastName and an id in memory but they are only accessible through any getters and setters methods we include. If you would like to access private fields of a parent class directly in a subclass you can choose to make those fields protected instead of private. 4. Add fields to the Student class. Don't forget to create/initialize the ArrayList. 5. Now we are going to fix the error related to the constructor. Let's first think about it. If we consider the process of constructing a subclass object we would realize that we need to initialize fields of both the superclass and the subclass. As a result, Java requires a subclass constructor to call the superclass constructor as the first job. This can be done implicitly if the superclass has a default constructor. However, there is no default constructor in the Person class, so we must call the non-default constructor explicitly. Th of 8 ZOOM + Page < constructor in the Person class, so we must call the non-default constructor explicitly. This is why there is the compiler error that you saw earlier. 6. To be able to initialize the fields defined in the Person class, the constructor of the Student class includes 6 parameters, three of which will be used to initialize the fields in the Person class. Add the header of the constructor in your Student class. 7. Now complete the constructor by adding statements to initialize all the fields including the ones defined in the Person class. Remember that the first statement in the constructor of any subclass must be the call to the constructor of the superclass. You can do this by using the keyword super() and since we want to initialize all the fields the Student class, including the ones defined in the Person class, we can use the second constructor: super (firstName, lastName, id) This calls the constructor of the superclass and initializes those fields with the parameters passed into the Student constructor. Don't forget to create/initialize the ArrayList. Your complete constructor might look like this: public Student (String fName, String lName, int id, String major, double gpa, int credits) { } super (fName, lName, id); major; 5 this.major this.gpa = gpa; this.credits = credits; = balance = 0; enrolledCourses = new ArrayList(); > 8. In Student.java, add the setters and getters you see listed in the UML class diagram. Remember that setters and getters are related to encapsulation. Refer to Unit 5 in the CS Awesome textbook for a refresher on encapsulation. 9. Next add the addCourse () and dropCourse () methods. Note that these methods are specific to the Student class. You can only apply them to Student objects, not Person objects. The addCourse () method adds the provided course to the ArrayList of courses for this student. The dropCourse () method removes the course from this list. If there is a course in the list that matches the course provided, remove the course from the list and return true. If there isn't a course in the list that matches, return false. of 8 ZOOM + Page < 8. In Student.java, add the setters and getters you see listed in the UML class diagram. Remember that setters and getters are related to encapsulation. Refer to Unit 5 in the CS Awesome textbook for a refresher on encapsulation. 5 9. Next add the addCourse () and dropCourse () methods. Note that these methods are specific to the Student class. You can only apply them to Student objects, not Person objects. The addCourse () method adds the provided course to the ArrayList of courses for this student. The dropCourse () method removes the course from this list. If there is a course in the list that matches the course provided, remove the course from the list and return true. If there isn't a course in the list that matches, return false. Think back to our ArrayList lab where we created methods just like these to update our ArrayList. 10. Let's test to make sure our subclass works. In the main method of your main class file, and add statements to create a Student object and test the different methods, like this: Student s1 = new Student("Xavier", "Cato", 900111222, "CS", 3.5, 75); s1.setTransfer(true); s1.setBalance (100); s1.addCourse ("Java Programming"); s1.addCourse ("Calculus"); s1.display(); if (s1.dropCourse ("Spanish")) { System out println("The class has been dropped") of 8 ZOOM + s1.setBalance (100); s1.addCourse ("Java Programming"); s1.addCourse("Calculus"); Student s1 = new Student ("Xavier", "Cato", 900111222, "CS", 3.5, 75); s1.setTransfer(true); s1.display(); if (s1.dropCourse ("Spanish")) { System.out.println("The class has been dropped"); } else { } System.out.println("You are not enrolled in this course. + "No courses have been dropped."); } 11. Run your project, and you should see an output similar to this: Output - 1213 Module6 (run) X DD run: DD on 54 Page < ArrayList enrolled Courses = s1.getEnrolledCourses(); System.out.println("You are enrolled in the following courses:"); for (String course : enrolled Courses) { System.out.println(course); *** Part A *** || Calculus BUILD SUCCESSFUL (total time: 0 seconds) 6 Name: Raya Whitaker ID: 800555555 *** Part B *** Name: Xavier Cato ID: 900111222 You are not enrolled in this course. No courses have been dropped. You are enrolled in the following courses: Java Programming 12. When your program works and you are satisfied with the result, show your work to the instructional team to get checked off and proceed to Part C. of 8 ZOOM + Part C 1. Follow the same procedure we followed in Part B to add the Professor class. The UML class diagram is as follows: Professor - department: String - salary: double - advisees: ArrayList + Professor(String, String, int, String, double) + getDepartment(): String + getSalary(): double + getAdvisees(): ArrayList + setDepartment(String): void + setSalary(double): void } + addAdvisee(Student): void + removeAdvisee(int): boolean 2. To test your Professor class add the following statement to the main method in the main class prof1.addAdvisee(s2); prof1.addAdvisee(s3); prof1.addAdvisee (s4); prof1.display(); Page < 7 System.out.println("*** Part C ***"' ) ; Student s2 = new Student ("Kathrine", "Johnson", 900, "CS", 4.0, 100); Student s3 = new Student ("Roy", "Clay", 901, "Biology", 3.2, 85); Student s4 = new Student("Kimberly", "Bryant", 902, "EE", 3.0, 80); Professor prof1 = new Professor("Mary", "Castro", 300, "CS", 80000); if (prof1.removeAdvisee (902)) { System.out.println("The advisee has been removed"); } else { System.out.println("This student is not an advisee of Professor + profl.getFirstName() + " " + profl.getLastName()); of 8 ZOOM + Page < ArrayList myAdvisees = prof1.getAdvisees(); System.out.println("Professor " + prof1.getFirstName() + + prof1.getLastName() + advisees:"); for (Student s: myAdvisees) { || 11 System.out.println(s.getFirstName() + + s.getLastName()); } 3. Run your project and fix any bugs you encounter. your output might look like this: *** Part C *** Name: Mary Castro ID: 300 The advisee has been removed Professor Mary Castro advisees: Kathrine Johnson Roy Clay BUILD SUCCESSFUL (total time: 0 seconds) 4. When your program works and you are satisfied with the result, show your work to the instructional team to get checked off for this lab. of 8 ZOOM + Bonus Add and generate JavaDoc for this project Page < So what did you learn in this lab? 1. How to extend a superclass 2. How to create appropriate constructor(s) in a subclass 3. How to use super to call methods in the superclass that have been overridden in the subclass of 8 ZOOM +
Expert Answer:
Answer rating: 100% (QA)
First well create a new project named InheritanceLab Then well create all necessary claess inside this project Lets create Person class Then well create instance variables and parameterized constructo... View the full answer
Related Book For
Fundamentals of corporate finance
ISBN: 978-0470876442
2nd Edition
Authors: Robert Parrino, David S. Kidwell, Thomas W. Bates
Posted Date:
Students also viewed these programming questions
-
Planning is one of the most important management functions in any business. A front office managers first step in planning should involve determine the departments goals. Planning also includes...
-
The following MINITAB output exhibits the cumulative distribution function curves of three lognormal distributions. Their mean and variance, respectively, are (1, .5), (1, 1), and (1, 2). Compare the...
-
A researcher measures job satisfaction among married, single, and divorced employees to determine whether marital status can influence job satisfaction. Based on the following description in APA...
-
If the weights of cement bags are normally distributed with a mean of 60 lb and a standard deviation of 1 lb, use the empirical rule to find the percent of the bags that weigh the following: More...
-
What is the default filename that make will process if no other is given?
-
The famous Y. S. Chang Restaurant is open 24 hours a day. Waiters and busboys report for duty at 3 A.M., 7 A.M., 11 A.M., 3 P.M., 7 P.M., or 11 P.M., and each works an 8-hour shift. The following...
-
4. A pharma company you work for makes jars with cream. It claims that the average amount of cream in a jar is at least 90 g. To prove that claim to the customers you decide to test the claim at a...
-
Bruce used 6 full boxes of tiles plus an additional 2 tiles, and Felicia used 5 full boxes of tiles plus an additional 17 tiles. If they each used the same number of tiles, how many tiles were in...
-
Describe people's knowledge and experience with business processes and systems of the UI program, and explain how they will bring this experience and expertise to the position as Manager and...
-
Mini Research Paper Sociologists study how society affects people and how people affect society. Think of a broad topic that you are interested in and which would make a good sociological study....
-
Question 3 The green-energy company Skylift develops techniques to harness the energy in high- altitude jet-stream winds. Skylift has successfully developed a way to use tethered kites to capture...
-
Compute the balances on each of the forms in figure 5 starting below. Enter the transactions in the purchases invoice register figure 6. Use 05011 as the account number for purchases discount and...
-
Capital budgeting information provided in their posts, discuss a cost consideration they did not include. Explain your rationale for stating that it is an important factor to be considered in the...
-
Fill in the missing values in the givne table. Table 1. Mass Dependence of the Period Length of Pendulum, L = 0.50 m angle=10 Mass A Single Period Tavg Tavg2 (sec2) (grams) (sec) (sec) 25 2.45 2.55...
-
Ask students to outline the reasons why the various elements of culture (social structures and control systems, language and aesthetics, religion and other belief systems, educational systems, etc.)...
-
The Fulcrum Company produces decorative swivel platforms for home televisions. If Fulcrum produces 40 million units, it estimates that it can sell them for $100 each. The variable production costs...
-
What is an agency relationship and what is an agency conflict? How can agency conflicts be reduced in a corporation?
-
List the profitability ratios discussed in this section, and explain how they differ from each other.
-
Construct a stem-and-leaf plot of the poverty data discussed in Example 6. Approach We will use Minitab. The steps for constructing the graphs using Minitab or StatCrunch are given in the Technology...
-
Draw a dot plot for the number of arrivals at Wendys data from Table 8. Approach The smallest observation in the data set is 1 and the largest is 11. Write the numbers 1 through 11 horizontally. For...
-
The following data represent the number of grams of fat in breakfast meals offered at a local fast food restaurant. (a) construct a stem-and-leaf plot and (b) describe the shape of the distribution....
Study smarter with the SolutionInn App