Java Day 12: Inheritance



You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are provided for you in the editor. Observe that Student inherits all the properties of Person.



  1. import java.util.*;
  2. class Person {
  3. protected String firstName;
  4. protected String lastName;
  5. protected int idNumber;
  6. // Constructor
  7. Person(String firstName, String lastName, int identification){
  8. this.firstName = firstName;
  9. this.lastName = lastName;
  10. this.idNumber = identification;
  11. }
  12. // Print person data
  13. public void printPerson(){
  14. System.out.println(
  15. "Name: " + lastName + ", " + firstName
  16. + "\nID: " + idNumber);
  17. }
  18. }
  19. class Student extends Person {
  20. private int[] testScores;
  21. Student(String firstName, String lastName, int identification, int[] testScores) {
  22. super(firstName, lastName, identification);
  23. this.testScores = testScores;
  24. }
  25. char calculate() {
  26. int total = 0;
  27. for (int testScore : testScores) total += testScore;
  28. int avg = total / testScores.length;
  29. if (avg >= 90 && avg <= 100) return 'O';
  30. if (avg >= 80 && avg < 90) return 'E';
  31. if (avg >= 70 && avg < 80) return 'A';
  32. if (avg >= 55 && avg < 70) return 'P';
  33. if (avg >= 40 && avg < 55) return 'D';
  34. return 'T';
  35. }
  36. }
  37. class Solution {
  38. public static void main(String[] args) {
  39. Scanner scan = new Scanner(System.in);
  40. String firstName = scan.next();
  41. String lastName = scan.next();
  42. int id = scan.nextInt();
  43. int numScores = scan.nextInt();
  44. int[] testScores = new int[numScores];
  45. for(int i = 0; i < numScores; i++){
  46. testScores[i] = scan.nextInt();
  47. }
  48. scan.close();
  49. Student s = new Student(firstName, lastName, id, testScores);
  50. s.printPerson();
  51. System.out.println("Grade: " + s.calculate() );
  52. }
  53. }