zoukankan      html  css  js  c++  java
  • 实验六20177101010119穷吉

    实验六继承定义与使用

    理论知识:

    继承的定义:可以基于已存在的类构造一个新类,继承已存在的类就是复用这些类的方法和域。

    继承的特点是具有层次结构,子类继承父类的方法和域。

    由继承Employee类来定义Manager类的格式,关键字extends表示继承。

    关键字extends表明正在构造的新类派生于一个已存在的类,已存在的类称为超类、基类、父类。新类称为子类。

     通过扩张超类定义子类的时候,仅需要指出子类与超类的不同之处。

    在子类中可以增加域、增加方法和覆盖超类的方法,然而就对不能删除继承的任何域和方法。

    继承层次:有一个公共超类派生出来的所有类的集合被称为继承层次。从某个特点定的类到其祖先的路径被称为该类的继承链。

    Java不支持多继承。

    多态性:多态性泛指在程序中同一个符号在不同的情况下具有不同解释的现象。

    超类中定义的域或方法,被子类继承之后,可以具有不同的数据类型或表现出不同的行为。

     这使得同一个域或方法在超类及其各个子类中具有不同的语义。

    超类中的方法在子类中可方法重写。

    静态域:用static修饰的域为静态域,也叫类域,否则为实例域。

    .静态方法:用static修饰的方法为静态方法或类方法,静态方法可通过类名或对象来调用。静态方法不能操作对象,所有不能在静态方法中访问实例域,但静态方法可以访问自身类中的静态域。

    .建议使用类名来调用静态方法。

    .使用静态方法的情况:(1)一个方法不需要访问对象状态(2)一个方法只需访问类的静态域。

    main方法是一个静态方法,启动程序时,静态main方法将执行并创建程序所需的对象。每一个类可以有一个main方法

     

    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;

     

    /**

     * 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;

     

    /**

     * This program demonstrates abstract classes.

     * @version 1.01 2004-02-21

     * @author Cay Horstmann

     */

    public class PersonTest

    {

       public static void main(String[] args)

       {

          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());

       }

    Ÿ   }

    测试程序3:

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

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

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

    Ÿ   Employee

    Ÿ   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 (this == otherObject) return true;

    Ÿ    

    Ÿ         // 如果显示参数为空,则必须返回False

    Ÿ         if (otherObject == null) return false;

    Ÿ    

    Ÿ         // 如果类不匹配他们就不相等

    Ÿ         if (getClass() != otherObject.getClass()) return false;

    Ÿ    

    Ÿ         // 现在我们知道另一个对象是非空雇员

    Ÿ         Employee other = (Employee) otherObject;

    Ÿ    

    Ÿ         // 测试字段是否具有相同的值

    Ÿ         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()

    Ÿ      {

    Ÿ         return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay

    Ÿ               + "]";

    Ÿ      }

    Ÿ   }

    Ÿ   Equals:

    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//子类Manager继承父类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;

    Ÿ         // super.equals检查这个和其他属于同一个类

    Ÿ         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)

       {

          // 对象用三个employ填充工作人员数组列表

          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());

       }

    Ÿ   }

    测试程序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

       public static void main(String[] args)

       { 

          Scanner 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 第二实验;

    abstract class Shape{

    double PI =3.14;

    public abstract double getperimeter();

    public  abstract double getArea();

    }

    abstract class Rectangle extends Shape{

       private int Width;

         private int Length;

         public Rectangle(int length ,int width) {

           this.Width =width;

           this .Length=length;

         }

         public double getperimeter() {

         int temp=(Width+Length)*2;

         return temp;

         }

         public double getArea() {

           int temp =(Width*Length);

           return temp;

         }

         }

    package 第二实验;
    import java.util.Scanner;
    public class Test {
     public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      System.out.println("个数");
      int a = in.nextInt();
      System.out.println("种类");
      String rect="rect";
            String cir="cir";
      Shape[] num=new Shape[a];
      for(int i=0;i<a;i++){
       String input=in.next();
       if(input.equals(rect)) {
       System.out.println("长和宽");
       int length = in.nextInt();
       int width = in.nextInt();
             num[i]=new Rectangle(width,length);
             System.out.println("Rectangle["+"length:"+length+"  "+width+"]");
             }
       if(input.equals(cir)) {
             System.out.println("半径");
          int radius = in.nextInt();
          num[i]=new Circle(radius);
          System.out.println("Circle["+"radius:"+radius+"]");
             }
             }
             Test c=new Test();
             System.out.println("求和");
             System.out.println(c.sumAllPerimeter(num));
             System.out.println(c.sumAllArea(num));
             
             for(Shape s:num) {
                 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;
               }    
    }

     

    实验3编程练习2

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

    package 第三实验;
    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 Main{
        private static ArrayList<Student> studentlist;
        public static void main(String[] args) {
            studentlist = 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 number = linescanner.next();
                    String sex = linescanner.next();
                    String year = linescanner.next();
                    String province =linescanner.nextLine();
                    Student student = new Student();
                    student.setName(name);
                    student.setnumber(number);
                    student.setsex(sex);
                    student.setyear(year);
                    student.setprovince(province);
                    studentlist.add(student);
     
                }
            } 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 studentname = scanner.next();
                    int nameint = findStudentByname(studentname);
                    if (nameint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + studentlist.get(nameint).getnumber() + "    姓名:"
                                + studentlist.get(nameint).getName() +"    性别:"
                                +studentlist.get(nameint).getsex()   +"    年龄:"
                                +studentlist.get(nameint).getyaer()+"  地址:"
                                +studentlist.get(nameint).getprovince()
                                );
                    } else {
                        System.out.println("不存在该学生");
                    }
                    break;
                case 2:
                    System.out.println("请输入身份证号");
                    String studentid = scanner.next();
                    int idint = findStudentByid(studentid);
                    if (idint != -1) {
                        System.out.println("查找信息为:身份证号:"
                                + studentlist.get(idint ).getnumber() + "    姓名:"
                                + studentlist.get(idint ).getName() +"    性别:"
                                +studentlist.get(idint ).getsex()   +"    年龄:"
                                +studentlist.get(idint ).getyaer()+"   地址:"
                                +studentlist.get(idint ).getprovince()
                                );
                    } else {
                        System.out.println("不存在该学生");
                    }
                    break;
                case 3:
                    isTrue = false;
                    System.out.println("程序已退出!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }
     
        public static int findStudentByname(String name) {
            int flag = -1;
            int a[];
            for (int i = 0; i < studentlist.size(); i++) {
                if (studentlist.get(i).getName().equals(name)) {
                    flag= i;
                }
            }
            return flag;
        }
     
        public static int findStudentByid(String id) {
            int flag = -1;
     
            for (int i = 0; i < studentlist.size(); i++) {
                if (studentlist.get(i).getnumber().equals(id)) {
                    flag = i;
                }
            }
            return flag;
        }   
    }

    package 第三实验;

     

    public class Student {

     

        private String name;

        private String number ;

        private String sex ;

        private String year;

        private String province;

      

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

        public String getnumber() {

            return number;

        }

        public void setnumber(String number) {

            this.number = number;

        }

        public String getsex() {

            return sex ;

        }

        public void setsex(String sex ) {

            this.sex =sex ;

        }

        public String getyaer() {

            return year;

        }

        public void setyear(String year ) {

            this.year=year ;

        }

        public String getprovince() {

            return province;

        }

        public void setprovince(String province) {

            this.province=province ;

        }

    }

    实验总结:通过这次实验里代码的注释我理解了代码的意思虽然有些英语还是不理解通过查找之后就可以理解,通过注释可以知道拿个部分定义了什么内容而不是盲目的去理解,通过学长的演示和自己的理解可以将用定义户类那些通过慢慢摸索可以自己进行编写。代码注释时就可以知道我们所学的理论知识都用到了那些方面,是怎样运用和实行的。

  • 相关阅读:
    Mac MySql突然不好用了,说权限不够
    关闭Nginx的进程
    Mac 设置域名解析
    Docker的Yml文件
    Docker遇到的异常和注意点
    MySQL 查询时间段内的数据
    golang martini 源码阅读笔记之martini核心
    golang martini 源码阅读笔记之inject
    使用erlang实现简单的二进制通信协议
    使用 erlang OTP 模式编写非阻塞的 tcp 服务器(来自erlang wiki)
  • 原文地址:https://www.cnblogs.com/qiongji/p/9750295.html
Copyright © 2011-2022 走看看