201771010106东文财《面向对象程序设计(java)》 实验6

实验六继承定义与使用

实验时间 2018-9-28

一.知识总结

1、继承的概述:在多个类中存在相同的属性和行为,把这些相同的部分抽取到一个单独的类中,把这个单独的类叫作父类,也叫基类或者超类,把其他被抽取的类叫作子类,并且父类的所有属性和方法(除private修饰的私有属性和方法外),子类都可以调用。这样的一种行为就叫做继承。(相同的东西在父类,不同的东西在子类)

2、继承的关键字:extends

3、继承的格式:class 子类名  extends  父类名{    }

4、在代码中使用继承提高了代码的复用性和维护性,让类与类直接产生了关系。

5、继承的注意点:

①子类只能继承父类所有的非私有的成员方法和成员变量,private修饰的不能继承。

②子类不能继承父类的构造方法,但可以通过   super   关键字去访问父类的构造方法。(先初始化父类,再执行自己)

③不同包不能继承。

 6、在使用  super  的时候,我们还需要了解关键字 super  和  this  的区别:

         super :到父类中去找方法,没有引用的作用;也可以用于其他方法中;与this调用构造方的重载一样,用于第一行。

         this:是指当前正在初始化的这个对象的引用。

二.实验部分:

1、实验目的与要求

(1) 理解继承的定义;

(2) 掌握子类的定义要求

(3) 掌握多态性的概念及用法;

(4) 掌握抽象类的定义及用途;

(5) 掌握类中4个成员访问权限修饰符的用途;

(6) 掌握抽象类的定义方法及用途;

(7)掌握Object类的用途及常用API;

(8) 掌握ArrayList类的定义方法及用法;

(9) 掌握枚举类定义方法及用途。

2、实验内容和步骤

实验1: 导入第5章示例程序,测试并进行代码注释。

测试程序1:

Ÿ   在elipse IDE中编辑、调试、运行程序5-1 (教材152页-153页) ;

Ÿ   掌握子类的定义及用法;

Ÿ   结合程序运行结果,理解并总结OO风格程序构造特点,理解Employee和Manager类的关系子类的用途,并在代码中添加注释。

package inheritance;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;
   //构建三个私有对象
   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}
package inheritance;

public class Manager extends Employee
//关键字extends表示继承。表明正在构造一个新类派生于一个已经存在的类。已经存在的类称为超类/基类/或者父类;新类称为子类/派生类/或者孩子类。 {
private double bonus; /** * @param name the employee's name * @param salary the salary * @param year the hire year * @param month the hire month * @param day the hire day */ public Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day);
//调用超类中含有n,s,year,month,day参数的构造器 bonus
= 0; } public double getSalary()
//子类要想访问要想访问超类中的方法需要使用特定的关键字super, {
double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } }
package inheritance;

/**
 * This program demonstrates inheritance.
 * @version 1.21 2004-02-21
 * @author Cay Horstmann
 */
public class ManagerTest
{
   public static void main(String[] args)
   {
      // 构建管理者对象
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);

      Employee[] staff = new Employee[3];

      //  用管理者和雇员对象填充工作人员数组

      staff[0] = boss;
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);

      // 打印所有员工对象的信息
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
   }
}

实验结果:

测试程序2:

Ÿ   编辑、编译、调试运行教材PersonTest程序(教材163页-165页);

Ÿ   掌握超类的定义及其使用要求;

Ÿ   掌握利用超类扩展子类的要求;

Ÿ   在程序中相关代码处添加新知识的注释。

package abstractClasses;

import java.time.*;

public class Employee extends Person
{
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      super(name);
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }
    //重写父类方法,返回一个格式化的字符串
   public String getDescription()
   {
      return String.format("an employee with a salary of $%.2f", salary);
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}
package abstractClasses;

public abstract class Person
{
//包含一个或多个抽象方法的类被称为抽象类,由abstract关键字修饰
public abstract String getDescription(); private String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
package abstractClasses;

/**
 * This program demonstrates abstract classes.
 * @version 1.01 2004-02-21
 * @author Cay Horstmann
 */
public class PersonTest
{
   public static void main(String[] args)
   {
//抽象类的声明,但不能将抽象类实例化 ,实例化的是Person类的子类 Person[] people
= new Person[2]; // 用学生和雇员填充人物数组

people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1); people[1] = new Student("Maria Morris", "computer science"); // 打印所有人对象的名称和描述 for (Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); } }
package abstractClasses;

public class Student extends Person
{
   private String major;

   /**
    * @param nama the student's name
    * @param major the student's major
    */
   public Student(String name, String major)
   {
      // 通过n to 总纲构造函数
      super(name);
      this.major = major;
   }

   public String getDescription()
   {
      return "a student majoring in " + major;
   }
}

实验结果:

测试程序3:

Ÿ   编辑、编译、调试运行教材程序5-8、5-9、5-10,结合程序运行结果理解程序(教材174页-177页);

Ÿ   掌握Object类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package equals;

import java.time.*;
import java.util.Objects;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }

   public boolean equals(Object otherObject)
   {
      //这里获得一个对象参数,第一个if语句判断两个引用是否是同一个,如果是那么这两个对象肯定相等
      if (this == otherObject) return true;

      //  如果显式参数为空,则必须返回false
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal
      if (getClass() != otherObject.getClass()) return false;

      // 现在我们知道另一个对象是非空雇员
      Employee other = (Employee) otherObject;

      // test whether the fields have identical values
      return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
   }

   public int hashCode()
   {
      return Objects.hash(name, salary, hireDay); 
   }

   public String toString()// toString()方法
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
}
package equals;

/**
 * This program demonstrates the equals method.
 * @version 1.12 2012-01-26
 * @author Cay Horstmann
 */
public class EqualsTest
{
   public static void main(String[] args)
   {
      Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee alice2 = alice1;
      Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
      Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);

      System.out.println("alice1 == alice2: " + (alice1 == alice2));

      System.out.println("alice1 == alice3: " + (alice1 == alice3));

      System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));

      System.out.println("alice1.equals(bob): " + alice1.equals(bob));

      System.out.println("bob.toString(): " + bob);

      Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);
      System.out.println("boss.toString(): " + boss);
      System.out.println("carl.equals(boss): " + carl.equals(boss));
      System.out.println("alice1.hashCode(): " + alice1.hashCode());
      System.out.println("alice3.hashCode(): " + alice3.hashCode());
      System.out.println("bob.hashCode(): " + bob.hashCode());
      System.out.println("carl.hashCode(): " + carl.hashCode());
   }
}
package equals;

public class Manager extends Employee
{
   private double bonus;

   public Manager(String name, double salary, int year, int month, int day)
   {
      super(name, salary, year, month, day);
      bonus = 0;
   }

   public double getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double bonus)
   {
      this.bonus = bonus;
   }

   public boolean equals(Object otherObject)
   {
      if (!super.equals(otherObject)) return false;
      Manager other = (Manager) otherObject;
      // 检查这个和其他属于同一个类
      return bonus == other.bonus;
   }

   public int hashCode()
   {
      return java.util.Objects.hash(super.hashCode(), bonus);
   }

   public String toString()
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}

实验结果:

测试程序4:

Ÿ   在elipse IDE中调试运行程序5-11(教材182页),结合程序运行结果理解程序;

Ÿ   掌握ArrayList类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package arrayList;

import java.util.*;

/**
 * This program demonstrates the ArrayList class.
 * @version 1.11 2012-01-26
 * @author Cay Horstmann
 */
public class ArrayListTest
{
   public static void main(String[] args)
   {
      // 用三个雇员对象填充工作人员数组列表    
ArrayList<Employee> staff = new ArrayList<>(); staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15)); staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1)); staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15)); //把每个人的薪水提高5% for (Employee e : staff) e.raiseSalary(5); // 打印所有员工对象的信息 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } }
package arrayList;

import java.time.*;

public class Employee
{
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {
      return salary;
   }

   public LocalDate getHireDay()
   {
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}
 

实验结果:

测试程序5:

Ÿ   编辑、编译、调试运行程序5-12(教材189页),结合运行结果理解程序;

Ÿ   掌握枚举类的定义及用法;

Ÿ   在程序中相关代码处添加新知识的注释。

package enums;

import java.util.*;

/**
 * This program demonstrates enumerated types.
 * @version 1.0 2004-05-24
 * @author Cay Horstmann
 */
public class EnumTest
{  
   private static Scanner in;

public static void main(String[] args)
   {  
      in = new Scanner(System.in);
      System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
      String input = in.next().toUpperCase();
      Size size = Enum.valueOf(Size.class, input);
      System.out.println("size=" + size);
      System.out.println("abbreviation=" + size.getAbbreviation());
      if (size == Size.EXTRA_LARGE)
         System.out.println("Good job--you paid attention to the _.");      
   }
}

enum Size
{
   SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;
}

实验结果:

实验2编程练习1

Ÿ   定义抽象类Shape:

属性:不可变常量double PI,值为3.14;

方法:public double getPerimeter();public double getArea())。

Ÿ   让Rectangle与Circle继承自Shape类。

Ÿ   编写double sumAllArea方法输出形状数组中的面积和和double sumAllPerimeter方法输出形状数组中的周长和。

Ÿ   main方法中

1)输入整型值n,然后建立n个不同的形状。如果输入rect,则再输入长和宽。如果输入cir,则再输入半径。
2) 然后输出所有的形状的周长之和,面积之和。并将所有的形状信息以样例的格式输出。
3) 最后输出每个形状的类型与父类型,使用类似shape.getClass()(获得类型),shape.getClass().getSuperclass()(获得父类型);

思考sumAllArea和sumAllPerimeter方法放在哪个类中更合适?

输入样例:

3

rect

1 1

rect

2 2

cir

1

输出样例:

18.28

8.14

[Rectangle [width=1, length=1], Rectangle [width=2, length=2], Circle [radius=1]]

class Rectangle,class Shape

class Rectangle,class Shape

class Circle,class Shape

package shape;

    import java.math.*;
    import java.util.*;
    import shape.shape;
    import shape.Rectangle;
    import shape.Circle;

    public class shapecount 
    {

        public static void main(String[] args) 
        {
            Scanner in = new Scanner(System.in);
            String rect = "rect";
            String cir = "cir";
            System.out.print("请输入形状个数:");
            int n = in.nextInt();
            shape[] score = new shape[n];
            for(int i=0;i<n;i++)
            {
                System.out.println("请输入形状类型 (rect or cir):");
                String input = in.next();
                if(input.equals(rect))
                {
                    double length = in.nextDouble();
                    double width = in.nextDouble();
                    System.out.println("Rectangle["+"length:"+length+"  "+width+"]");
                    score[i] = new Rectangle(width,length);
                }
                if(input.equals(cir)) 
                {
                    double radius = in.nextDouble();
                    System.out.println("Circle["+"radius:"+radius+"]");
                    score[i] = new Circle(radius);
                }
            }
            shapecount c = new shapecount();
            System.out.println(c.sumAllPerimeter(score));
            System.out.println(c.sumAllArea(score));
            for(shape s:score) 
            {

                System.out.println(s.getClass()+",  "+s.getClass().getSuperclass());
            }
        }

        public double sumAllArea(shape score[])
        {
             double sum = 0;
             for(int i = 0;i<score.length;i++)
                 sum+= score[i].getArea();
             return sum;
        }
        
        public double sumAllPerimeter(shape score[])
        {
             double sum = 0;
             for(int i = 0;i<score.length;i++)
                 sum+= score[i].getPerimeter();
             return sum;
        }
        
    }
    package shape;

    public class Rectangle extends shape
    {
        private double width;
        private double length;
        public Rectangle(double w,double l)
        {
            this.width = w;
            this.length = l;
        }
        public double getPerimeter()
        {
            double Perimeter = (width+length)*2;
            return Perimeter;
        }
        public double getArea()
        {
            double Area = width*length;
            return Area;
        }

          public String toString()
          {
              return getClass().getName() + "[ width=" +  width + "]"+ "[length=" + length + "]";
          }
    }
    package shape;

    public abstract class shape
    {
        double PI = 3.14;
        public abstract double  getPerimeter();
        public abstract double  getArea();
    }
package shape;

    public class Circle extends shape
    {

        private double radius;
        public Circle(double r)
        {
            radius = r;
        }
        public double getPerimeter()
        {
            double Perimeter = 2*PI*radius;
            return Perimeter;
        }
        public double getArea()
        {
            double Area = PI*radius*radius;
            return Area;
        }
        public String toString()
          {
              return  getClass().getName() + "[radius=" + radius + "]";
       }  
    }

实验结果:

 

实验3编程练习2

编制一个程序,将身份证号.txt 中的信息读入到内存中,输入一个身份证号或姓名,查询显示查询对象的姓名、身份证号、年龄、性别和出生地。

package qq;


    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Scanner;

    public class Test{
        private static ArrayList<Citizen> citizenlist;
        public static void main(String[] args) {
            citizenlist = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("D:\\身份证号.txt");
            try {
                FileInputStream fis = new FileInputStream(file);
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    Scanner linescanner = new Scanner(temp);
                    
                    linescanner.useDelimiter(" ");    
                    String name = linescanner.next();
                    String id = linescanner.next();
                    String sex = linescanner.next();
                    String age = linescanner.next();
                    String address =linescanner.nextLine();
                    Citizen citizen = new Citizen();
                    citizen.setName(name);
                    citizen.setId(id);
                    citizen.setSex(sex);
                    citizen.setAge(age);
                    citizen.setAddress(address);
                    citizenlist.add(citizen);

                }
            } catch (FileNotFoundException e) {
                System.out.println("信息文件找不到");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("信息文件读取错误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {

                System.out.println("1.按姓名查询");
                System.out.println("2.按身份证号查询");
                System.out.println("3.退出");
                int nextInt = scanner.nextInt();
                switch (nextInt) {
                case 1:
                    System.out.println("请输入姓名");
                    String citizenname = scanner.next();
                    int nameint = findCitizenByname(citizenname);
                    if (nameint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + citizenlist.get(nameint).getId() + "    姓名:"
                                + citizenlist.get(nameint).getName() +"    性别:"
                                +citizenlist.get(nameint).getSex()   +"    年龄:"
                                +citizenlist.get(nameint).getAge()+"  地址:"
                                +citizenlist.get(nameint).getAddress()
                                );
                    } else {
                        System.out.println("不存在该公民");
                    }
                    break;
                case 2:
                    System.out.println("请输入身份证号");
                    String citizenid = scanner.next();
                    int idint = findCitizenByid(citizenid);
                    if (idint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + citizenlist.get(idint ).getId() + "    姓名:"
                                + citizenlist.get(idint ).getName() +"    性别:"
                                +citizenlist.get(idint ).getSex()   +"    年龄:"
                                +citizenlist.get(idint ).getAge()+"   地址:"
                                +citizenlist.get(idint ).getAddress()
                                );
                    } else {
                        System.out.println("不存在该公民");
                    }
                    break;
                case 3:
                    isTrue = false;
                    System.out.println("程序已退出!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }

        public static int findCitizenByname(String name) {
            int flag = -1;
            int a[];
            for (int i = 0; i < citizenlist.size(); i++) {
                if (citizenlist.get(i).getName().equals(name)) {
                    flag= i;
                }
            }
            return flag;
        }

        public static int findCitizenByid(String id) {
            int flag = -1;

            for (int i = 0; i < citizenlist.size(); i++) {
                if (citizenlist.get(i).getId().equals(id)) {
                    flag = i;
                }
            }
            return flag;
        }   
    }
package qq;


    public class Citizen {

        private String name;
        private String id ;
        private String sex ;
        private String age;
        private String address;
       
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getSex() {
            return sex ;
        }
        public void setSex(String sex ) {
            this.sex =sex ;
        }
        public String getAge() {
            return age;
        }
        public void setAge(String age ) {
            this.age=age ;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address=address ;
        }
    }

实验结果:

实验总结:

     上周我们学习了第五章,这章中主要学了继承这一概念,通过继承人们可以在已存在的类构造一个新类,继承已存在的类就是复用这些类的方法和域,通过继承这一概念我们学习了一些类的概念如:超类,基类(父类),子类等。总的来说本章的知识点也是比较重要的,不过我对本章的知识掌握的不是很好,我会继续努力的,多多敲代码。

原文地址:https://www.cnblogs.com/D980321/p/9739816.html