Java experiment five polymorphism

Experimental report of School of computer science, Central South University

Course name Java object oriented programming SSD3

Name of experiment project experiment 5 object oriented polymorphism

Student name Xi_Chen123 professional class ******* class number ***********

Experiment result date

Experimental class hours: 2

Number of people in each group: 1

Experiment type: 1 (1: basic 2: comprehensive 3: Design 4: Research)

Experimental requirements: 1 (1: compulsory 2: elective 3: other)

Experiment category: 2 (1: foundation 2: major foundation 3: major 4: others)

  • Experimental purpose
  1. Understanding polymorphism and dynamic binding
  2. Storing, extracting, and manipulating objects in an ArrayList

2, Experiment content

   1. [Person, Student and Employee] (Note: this topic is modified from the original topic in the book) design a class named Person and its two subclasses named Student and Employee.

Everyone has a name and phone number. Students have grade status (freshman, sophomore, junior or senior). Define these states as constants. An employee has a salary and a date of employment. Define a class named MyDate, which contains data fields: year, month, and day. Encapsulate the data fields of each class, and set up reasonable read-write accessors.

Override the toString method in each class, and return a string composed of the class name and all the information available in the corresponding class. For example, the toString method of the Person class returns "Person class: name * * * phone * * *"; The toString method of Student class returns "Student class: name * * * phone * * * grade * * *".

Add the displayObject() method to the Student and Employee classes respectively to print out prompt messages for students and employees, prompting students to "to * * * (Student name): please hand in the experiment report on time" and employees to "to * * * (Employee name): please go to work on time".

Target output task:

  • Draw UML diagrams of these classes.
  • Implement these classes.
  • Write a test class, 1) create the method public static void m1(Person p), and display the name of p; 2) Create the method public static void m2(Person p), and print the string returned by the toString method of p; 3) Create the method public static void m3(Person p). If P is an instance of Student class or Employee class, call their displayObject() respectively; 4) Create object instances of Person, Student and Employee in the main function and declare them as Person class objects. They are introduced into m1, m2 and M3 respectively to realize polymorphism.

2. (P380, 11.5) [Course] rewrite the Course class in program list 10-6. Use ArrayList instead of arrays to store students. The original contract of the Course class should not be changed (that is, do not change the method header definitions of the constructor and method, including the return type, method name and parameter list, but the private members can be changed).

Procedure list 10-6

public class Course {

  private String courseName;

  private String[] students = new String[100];

  private int numberOfStudents;

   

  public Course(String courseName) {

    this.courseName = courseName;

  }

  public void addStudent(String student) {

    students[numberOfStudents] = student;

    numberOfStudents++;

  }

  public String[] getStudents() {

    return students;

  }

  public int getNumberOfStudents() {

    return numberOfStudents;

  } 

  public String getCourseName() {

    return courseName;

  } 

  public void dropStudent(String student) {

     }

}

Procedure list 10-5

[Note: please refer to the following procedure to test the Course class, and add necessary code on the basis of this procedure to completely test all the methods defined in the Course class]

public class TestCourse {
  public static void main(String[] args) {
    Course course1 = new Course("Data Structures");
    Course course2 = new Course("Database Systems");
 
    course1.addStudent("Peter Jones");
    course1.addStudent("Brian Smith");
    course1.addStudent("Anne Kennedy");
 
    course2.addStudent("Peter Jones");
    course2.addStudent("Steve Smith");
 
    System.out.println("Number of students in course1: "
      + course1.getNumberOfStudents());
    String[] students = course1.getStudents();
    for (int i = 0; i < course1.getNumberOfStudents(); i++)
      System.out.print(students[i] + ", ");
    
    System.out.println();
    System.out.print("Number of students in course2: "
      + course2.getNumberOfStudents());
  }
}

3. (P381, 11.10) (use inheritance to implement MyStack) in listing 11-10, MyStack is implemented by composition. Extend ArrayList to create a new stack class. Implement the MyStack class. Write a test program that prompts the user to enter five strings, and then display them in reverse order.

3, Test requirements:

Each student is required to complete the experimental task independently.

4, Experimental report

1. complete the experiment of this project within one week, and submit the experiment documents on the visual platform, including: The java file (corresponding to the above three questions respectively, and no.Class file is required) is packaged into a file named "Experiment 5" rar or zip file and one experiment report (see the following for format and requirements). The report is named "class name" (such as "2101")_ Student ID_ Name_ Experiment 5 doc”.

2. experimental results and analysis

(including UML diagram, operation result screenshot, etc.)

Experiment 1:

Experiment 2:

Experiment 3:

3. experience

(record the experience of the experiment, difficulties encountered in the process of using the computer, solutions, remaining problems, opinions and suggestions, etc.)

During the preparation of Experiment 1, the number of classes required was large and the relationship was slightly complex. Therefore, it took some time to sort out the relationship between classes. The Student and employee classes inherit from the Person class. In the Employee class, there is also a private data field of MyData class that needs to be declared. Plus the Demo class, there are five classes in total. The relationship between them needs to be clarified.

In the process of writing experiment 2, first of all, you need to understand the use format and function of common API s in the tool class ArrayList class, such as add()/get()/remove(). Secondly, according to the topic requirements, when modifying the Course class, we need to keep the original contract in the class the same as before, so that after modifying the class, we can ensure the normal operation of the relevant programs that used the interface in the past.

To keep the interface consistent, in the method of getStudents(), you need to create an array of String type, save the data in the ArrayList through the for loop, and finally return the array to maintain the original contract in the class.

In the process of writing experiment 3, we also encountered the problem of array index out of bounds. The reason is that in the process of deleting students, the numberOfStudents element in the Course class did not increase or decrease automatically, resulting in data errors. Such errors should be noted in future programming

exercise1

        exercise1Demo

package com.xc5.exercise1;

import javax.xml.crypto.Data;

public class exercise1Demo {
    public static void main(String[] args) {
        //create object
        Person person=new Person("Zhang San",110);
        Person xiaoMing=new Student("Xiao Ming",120,"Sophomore");
        MyData d=new MyData(2022,5,1);
        Person laoWang=new Employee("Lao Wang",119,3200.5,d);

        //Output interface
        m1(person);
        m1(xiaoMing);
        m1(laoWang);

        m2(person);
        m2(xiaoMing);
        m2(laoWang);

        m3(person);
        m3(xiaoMing);
        m3(laoWang);
    }


    //Show name of p
    public static void m1(Person p){
        System.out.println(p.getName());
    }

    //Print the string returned by the toString method of p
    public static void m2(Person p){
        System.out.println(p.toString());
    }

    //If p is an instance of the Student or Employee class, their displayObject() is called
    public static void m3(Person p){
        if(p instanceof Student){
            ((Student) p).displayObject();
        }

        if(p instanceof Employee){
            ((Employee) p).displayObject();
        }
    }
}

        Emolpyee

package com.xc5.exercise1;

public class Employee extends Person{
    private double salary;
    private MyData data;

    public Employee() {
    }

    public Employee(String name, long phoneNumber, double salary, MyData data) {
        super(name, phoneNumber);
        this.salary = salary;
        this.data = data;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public MyData getData() {
        return data;
    }

    public void setData(MyData data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Employee Class: name is"+getName()+" Phone is"+getPhoneNumber()+" Salary is"+getSalary()+" Date of entry"+getData();
    }

    public void displayObject(){
        System.out.println("to "+getName()+" : Please go to work on time");
    }
}

        MyData

package com.xc5.exercise1;

public class MyData {
    private int year;
    private int mouth;
    private int day;

    public MyData() {
    }

    public MyData(int year, int mouth, int day) {
        this.year = year;
        this.mouth = mouth;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public int getMouth() {
        return mouth;
    }

    public int getDay() {
        return day;
    }

    @Override
    public String toString() {
        return getYear()+"year"+getMouth()+"month"+getDay()+"day";
    }
}

        Person

package com.xc5.exercise1;

public class Person {
    private String name;
    private long phoneNumber;

    public Person() {
    }

    public Person(String name, long phoneNumber) {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(long phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public String toString(){
        return "Person Class: name is"+getName()+" Phone is"+getPhoneNumber();
    }
}

        Student

package com.xc5.exercise1;

public class Student extends Person{

    private String grade;

    public Student() {
    }

    public Student(String name, long phoneNumber, String grade) {
        super(name, phoneNumber);
        this.grade = grade;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String toString(){
        return "Student Class: name is"+getName()+" Phone is"+getPhoneNumber()+" Grade is"+getGrade();
    }

    public void displayObject(){
        System.out.println("to "+getName()+" : Please hand in the experiment report on time");
    }
}

exercise2

        Course

package com.xc5.exercise2;

import java.util.ArrayList;

public class Course {
    private String courseName;
    private ArrayList<String> students=new ArrayList<>();
    private int numberOfStudents;

    public Course(){
    }

    public Course(String courseName){
        this.courseName=courseName;
    }

    public void addStudent(String students){
        this.students.add(students);
        numberOfStudents++;
    }

    public String[] getStudents() {
        String[] students=new String[numberOfStudents];
        for(int i=0;i<numberOfStudents;i++){
            students[i]=this.students.get(i);
        }
        return students;
    }

    public int getNumberOfStudents() {
        return numberOfStudents;
    }

    public String getCourseName() {
        return courseName;
    }

    public void dropStudent(String students){
        for(int i=0;i<numberOfStudents++;i++){
            if(students==this.students.get(i)){
                this.students.remove(i);
            }
        }

        numberOfStudents--;
    }
}

        TestCourse

package com.xc5.exercise2;

public class TestCourse {
    public static void main(String[] args) {
        Course course1 = new Course("Data Structures");
        Course course2 = new Course("Database Systems");

        course1.addStudent("Peter Jones");
        course1.addStudent("Brian Smith");
        course1.addStudent("Anne Kennedy");

        course2.addStudent("Peter Jones");
        course2.addStudent("Steve Smith");

        System.out.println("Number of students in "+course1.getCourseName()+": " + course1.getNumberOfStudents());
        String[] students = course1.getStudents();
        for (int i = 0; i < course1.getNumberOfStudents(); i++)
            System.out.print(students[i] + ", ");

        System.out.println();
        System.out.println("Before deleting students");
        System.out.print("Number of students in course2"+course2.getCourseName()+": " + course2.getNumberOfStudents());
        String[] students2=course2.getStudents();
        for(int i=0;i<course2.getNumberOfStudents();i++){
            System.out.print(students2[i]+", ");
        }

        course2.dropStudent("Steve Smith");

        System.out.println();
        System.out.println("After deleting students");
        System.out.print("Number of students in course2"+course2.getCourseName()+": " + course2.getNumberOfStudents());
        students2=course2.getStudents();
        for(int i=0;i<course2.getNumberOfStudents();i++){
            System.out.print(students2[i]+", ");
        }
    }

}

exercise1

        MyStack

package com.xc5.exercise3;

public class MyStack extends java.util.ArrayList {
    public boolean isEmpty() {
        return this.isEmpty();
    }

    public int getSize() {
        return this.size();
    }

    public Object peek() {
        return this.get(getSize() - 1);
    }

    public Object pop() {
        Object object = this.get(this.size() - 1);
        this.remove(this.size() - 1);
        return object;
    }

    public void push(Object object) {
        this.add(object);
    }

    @Override
    public String toString() {
        return "Stack:\n"+"isEmpty: "+isEmpty()+"\nsize: "+getSize();
    }
}

        MyStackDemo

package com.xc5.exercise3;

import java.util.Scanner;

public class MyStackDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter 5 elements:");
        MyStack myStack = new MyStack();
        for(int i = 0; i < 5; i++){
            myStack.push(sc.next());
        }
        System.out.println("Display in reverse order:");
        for(int i = 0; i < 5; i++){
            System.out.print(myStack.pop());
            System.out.print(" ");
        }
    }
}

Tags: Java intellij-idea Software Engineering

Posted by mr02077 on Wed, 01 Jun 2022 08:51:20 +0530