201771010130王志成《面向对象程序设计(java)》第六周学习总结

一,理论学习部分

继承:用已有类来构建新类的一种机制。当定 义了一个新类继承了一个类时,这个新类就继 承了这个类的方法和域,同时在新类中添加新 的方法和域以适应新的情况。

多态性的概念(Polymorphism ) – 多态性泛指在程序中同一个符号在不同的情况 下具有不同解释的现象。 – 超类中定义的域或方法,被子类继承之后,可 以具有不同的数据类型或表现出不同的行为。 – 这使得同一个域或方法在超类及其各个子类中 具有不同的语义。 – 超类中的方法在子类中可方法重写。



一,实验内容

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类的关系子类的用途,并在代码中添加注释。

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;
   }
}
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);
      bonus = 0;
   }

   public double getSalary()
//提供一个新的方法 {
double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } }
 
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];

      //用Manager和Employee对象填充staff数组

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

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

测试程序2:

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

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

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

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

public abstract class Person
//建立一个超类
{
   public abstract String getDescription();
   private String name;

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

   public String getName()
   {
      return name;
   }
}
import java.time.*;

public class Employee extends Person
//person类继承employee类
{
   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);
      //字符串类型格式化采用format()方法
   }

   public void raiseSalary(double byPercent)
   {
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}
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传递给父类构造函数
      super(name);
      this.major = major;
   }

   public String getDescription()
   {
      return "a student majoring in " + major;
   }
}
public class PersonTest
{
   public static void main(String[] args)
   {
      Person[] people = new Person[2];

      // 用Student和Employee对象填充人员数组
      people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      people[1] = new Student("Maria Morris", "computer science");

      //  打印所有Person对象的名称和描述
      for (Person p : people)
         System.out.println(p.getName() + ", " + p.getDescription());
   }
}

测试程序3:

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

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

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

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

      // 现在我们知道otherObject是一个非空雇员
      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
            + "]";
   }
}
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:

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

2)掌握ArrayList类的定义及用法;

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

  import java.util.*;
 
 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:

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

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

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

import java.util.*;

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

1)定义抽象类Shape:

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

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

2)让Rectangle与Circle继承自Shape类。

3)编写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 wzc;

 
  

import java.math.*;
import java.util.*;

public class calculate

{

 
  

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String rect = "rect";
String cir = "cir";
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:"+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);
}
}
calculate c = new calculate();
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 wzc;

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

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

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

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 ID {

    public static People findPeopleByname(String name) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getName().equals(name)) {
                flag = people;
            }
        }
        return flag;

    }

    public static People findPeopleByid(String id) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getnumber().equals(id)) {
                flag = people;
            }
        }
        return flag;

    }
       
    private static ArrayList<People> peoplelist; 
    
    public static void main(String[] args) {
        peoplelist = new ArrayList<People>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\身份证号.txt");
        try {
            FileInputStream files = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(files));
            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 age = linescanner.next();
                String place = linescanner.nextLine();
                People people = new People();
                people.setName(name);
                people.setnumber(number);
                people.setage(age);
                people.setsex(sex);
                people.setplace(place);
                peoplelist.add(people);

            }
        } 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 peoplename = scanner.next();
                People people = findPeopleByname(peoplename);
                if (people != null) {
                    System.out.println("   姓名:"+ people.getName() +
                                       "  身份证号:"+ people.getnumber() +
                                       "   年龄:"+ people.getage()+
                                       "   性别:"+ people.getsex()+
                                       "   地址:"+ people.getplace()
                            );
                } else {
                    System.out.println("不存在此人");
                }
                break;
            case 2:
                System.out.println("请输入身份证号:");
                String peopleid = scanner.next();
                People people1 = findPeopleByid(peopleid);
                if (people1 != null) {
                    System.out.println("   姓名:"+ people1.getName()+
                                       "  身份证号:"+ people1.getnumber()+
                                       "   年龄:"+ people1.getage()+
                                       "   性别:"+ people1.getsex()+
                                       "   地址:"+ people1.getplace());
                } else {
                    System.out.println("不存在此人");
                }
                break;
            case 3:
                isTrue = false;
                System.out.println("byebye!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }


}
package IDcard;

public class People {

    private    String name;
    private    String number;
    private    String age;
    private    String sex;
    private    String place;

    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 getage() 
    {
        return age;
    }
    public void setage(String age ) 
    {
        this.age = age;
    }
    public String getsex() 
    {
        return sex;
    }
    public void setsex(String sex ) 
    {
        this.sex = sex;
    }
    public String getplace() 
    {
        return place;
    }
    public void setplace(String place) 
    {
        this.place = place;
    }
}

 总结:通过前一周的学习,我初步了解有关继承类的知识。在编写程序时,使用继承类更能简化程序。通过课堂学习和课后运行程序,了解了子类和父类的关系。另外,学习了抽象类的用法,在运行程序的过程中,加深了对它的理解。但却无法真正的运用于实践当中,面对所敲代码无法通过,各种语法错误,使我深深的意识到自己的知识掌握还远远不够,最终还是借助了同学的帮助,让他给我讲解了他所写的代码。才使得作业得以完成。今后一定要自主学习,逐步消化课堂中学习的内容。

猜你喜欢

转载自www.cnblogs.com/847118824wang/p/9736690.html