狄慧201771010104《面向对象程序设计(java)》第六周学习总结

实验六继承定义与使用

实验时间 2018-9-28

1、知识点总结

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

继承的特点:具有层次结构;子类继承了超类的方法和域。

2)类继承的格式:class 新类名 extends 已有类名

已有类称为:超类(superclass)、基类(base class) 或父类(parent  class)

新类称作:子类(subclass)、派生类(derived  class)或孩子类(child class)

1>继承类中,子类的构造器不能直接访问超类的私有域,必须调用超类构造器,且必须是第一条语句。

2>子类不能直接访问超类的私有域,必须和其他方法一样使用公有接口。

3>子类中可以增加域、增加方法或覆盖(override)超类的方法,但是绝不能删除超类的任何域和方法。

注:java不支持多继承。

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

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

java中,对象变量是多态的。

继承层次结构中,每个子类对象也可视作超类对象,因此,也可以将子类对象赋给超类变量。如:boss.setBouns(5000);

4)final类:不允许继承的类,在类的定义中用final修饰符加以说明。

5)强制转换类型:如果要把一个超类对象赋给一个子类对象变量,就必须进行强制类型转换,格式如下:Manager boss=(Manager)staff【0】;

6)抽象类:abstract class Person

1>abstract方法不能被实例化,即只能声明,不能实现!

2>包含一个或多个抽象方法的类本身必须被声明为抽象类。

7)Object类:所有类的超类。

8)equals方法:用于测试某个对象是否和另一个对象相等。如果两个对象有相同的引用,则他们一定相等。

9)hasCode方法:导出某个对象的散列码(任意整数)。

两个相等对象的散列码相等。

10)toString方法:返回一个代表该对象域值的字符串。

格式:类名【域值】

11)枚举类:它包括一个关键字enum,一个新枚举类型的名字 Grade以及为Grade定义的一组值,这里的值既非整型,亦非字符型。

1>枚举类是一个类,它的隐含超类是java.lang.Enum。

2>枚举值并不是整数或其它类型,是被声明的枚举类的自身实例

2.实验目的与要求

(1) 理解继承的定义;

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

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

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

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

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

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

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

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

3.实验内容和步骤

实验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;//加薪=薪水*加薪百分比/100
      salary += raise;//薪水赋值为加薪+薪水
   }
}
package inheritance;

public class Manager extends Employee
{
   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;//补贴为0
   }

   public double getSalary()//创建类浮点型得到薪水
   {
      double baseSalary = super.getSalary();//浮点型基本薪水赋值为父类对象雇员得到的薪水
      return baseSalary + bonus;//返回基本薪水+补贴
   }

   public void setBonus(double b)//创建一个空类补贴(浮点型b)
   {
      bonus = b;//补贴赋值为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)
   {
      // construct a Manager object(构造一个经理的对象)
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);//创建一个经理CC,工资、入职时间
      boss.setBonus(5000);//老板的补贴5000

      Employee[] staff = new Employee[3];//创建职员为3的数组

      // fill the staff array with Manager and Employee objects(填写经理和雇员对象的职员数组)

      staff[0] = boss;//将BOSS赋值给职员数组0
      staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);//将HH雇员赋值给职员数组1
      staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);//将TT雇员赋值给职员数组2

      // print out information about all Employee objects//输出所有雇员对象的信息
      for (Employee e : staff)//循环职员数组e
         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
{
   public abstract String getDescription();//
   private String name;//创建私有类字符串姓名

   public Person(String name)//创建人们类(字符串姓名)
   {
      this.name = name;//当前对象赋值
   }

   public String getName()//创建类得到姓名
   {
      return name;//返回姓名
   }
}
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)//类学生(姓名、专业)
   {
      // pass n to superclass constructor  途径是超类函数构造器
      super(name);//父类对象人
      this.major = major;//赋值专业
   }

   public String getDescription()
   {
      return "a student majoring in " + major;//返回,,,+专业
   }
}
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];//创建一个人为2的数组

      // fill the people array with Student and Employee objects//将学生、雇员对象填充到数组
      people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
      people[1] = new Student("Maria Morris", "computer science");

      // print out names and descriptions of all Person objects//输出所有人对象的姓名和描述
      for (Person p : people)//循环此数组p
         System.out.println(p.getName() + ", " + p.getDescription());//输出姓名,描述
   }
}

测试程序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)//相同类(对象 其他对象)
   {
      // a quick test to see if the objects are identical(一个快速检测对象是否一样)
      if (this == otherObject) return true;//如果此对象是其他对象,返回true

      // must return false if the explicit parameter is null(如果明确的参数是空的,必须返回false)
      if (otherObject == null) return false;//如果其他对象是空的,返回false

      // if the classes don't match, they can't be equal(如果类不能匹配,他们不相同)
      if (getClass() != otherObject.getClass()) return false;//这个类和其他类不匹配

      // now we know otherObject is a non-null Employee(现在我们知道其他类是一个非空的雇员类)
      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()
   {
      return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
            + "]";
   }
}
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;//奖金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 checked that this and other belong to the same class(父类  检查两个对象是否属于同一个类)
      return bonus == other.bonus;//返回相等
   }

   public int hashCode()//创建类重新编码
   {
      return java.util.Objects.hash(super.hashCode(), bonus);//返回
   }

   public String toString()
   {
      return super.toString() + "[bonus=" + bonus + "]";
   }
}
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);//将雇员AA的值赋给雇员a1
      Employee alice2 = alice1;//将a1赋值给雇员a2
      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);//将经理CC赋值给经理car1
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);//老板奖金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());
   }
}

测试程序4:

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

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

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

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;
   }
}
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)
   {
      // fill the staff array list with three Employee objects(填全体员工的数组表用三个雇员对象)
      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));

      // raise everyone's salary by 5%(增加每个人的薪水5%)
      for (Employee e : staff)
         e.raiseSalary(5);

      // print out information about all Employee objects(输出关于所有雇员对象的信息)
      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

import java.util.Scanner;

public class Shap
{

    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[] count = new shape[n];
        for(int i=0;i<n;i++)
        {
            System.out.println("请输入图形形状:");
            String input = in.next();
            if(input.equals(rect))
            {
                double length = in.nextDouble();
                double width = in.nextDouble();
                System.out.println("长方形:"+"长:"+length+"  宽:"+width);
                count[i] = new Rect(length,width);
            }
            if(input.equals(cir)) 
            {
                double radius = in.nextDouble();
                System.out.println("圆:"+"半径:"+radius);
                count[i] = new Cir(radius);
            }
        }
        Shap c = new Shap();
        System.out.println(c.sumAllPerimeter(count));
        System.out.println(c.sumAllArea(count));
        for(shape s:count) 
        {

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

    public double sumAllArea(shape count[])
    {
         double sum = 0;
         for(int i = 0;i<count.length;i++)
             sum+= count[i].getArea();
         return sum;
    }
    
    public double sumAllPerimeter(shape count[])
    {
         double sum = 0;
         for(int i = 0;i<count.length;i++)
             sum+= count[i].getPerimeter();
         return sum;
    }
    
}
public abstract class shape
 {
     double PI = 3.14;
     public abstract double  getPerimeter();
     public abstract double  getArea();
 }
public class Cir extends shape
{
    private double radius;
 
    public Cir(double radius2) {
        // TODO Auto-generated constructor stub
    }
    public double getPerimeter()
    {
        double Perimeter=2*PI*radius;
        return Perimeter;
    }
    public double getArea()
    {
        double Area=PI*radius*radius;
        return Area;
    }
}
public class Rect extends shape
{
    private double width;
    private double length;
    public Rect(double w,double l)
    {
        this.width = w;
        this.length = l;
    }
    public double getPerimeter()
    {
        double Perimeter = 2*(length+width);
        return Perimeter;
    }
    public double getArea()
    {
        double Area = length*width;
        return Area;
    }
}

实验3编程练习2

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

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<Person> personlist;
    public static void main(String[] args) {
        personlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("E:/java/身份证号.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();
                Person person = new Person();
                person.setName(name);
                person.setId(id);
                person.setSex(sex);
                person.setAge(age);
                person.setAddress(address);
                personlist.add(person);

            }
        } 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 personname = scanner.next();
                int nameint = findPersonByname(personname);
                if (nameint != -1) {
                    System.out.println("查找信息为:身份证号:"
                            + personlist.get(nameint).getId() + "    姓名:"
                            + personlist.get(nameint).getName() +"    性别:"
                            + personlist.get(nameint).getSex()   +"    年龄:"
                            + personlist.get(nameint).getAge()+"  地址:"
                            + personlist.get(nameint).getAddress()
                            );
                } else {
                    System.out.println("不存在该公民");
                }
                break;
            case 2:
                System.out.println("请输入身份证号");
                String personid = scanner.next();
                int idint = findPersonByid(personid);
                if (idint != -1) {
                    System.out.println("查找信息为:身份证号:"
                            + personlist.get(idint ).getId() + "    姓名:"
                            + personlist.get(idint ).getName() +"    性别:"
                            + personlist.get(idint ).getSex()   +"    年龄:"
                            + personlist.get(idint ).getAge()+"   地址:"
                            + personlist.get(idint ).getAddress()
                            );
                } else {
                    System.out.println("不存在该公民");
                }
                break;
            case 3:
                isTrue = false;
                System.out.println("程序已退出!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }

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

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

        for (int i = 0; i < personlist.size(); i++) {
            if (personlist.get(i).getId().equals(id)) {
                flag = i;
            }
        }
        return flag;
    }   
}
public class Person {

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

 

四.实验总结

       通过本周的学习,我初步掌握了有关继承类的知识,理解了父类和子类的定义,知道了继承指的是子类继承父类的方法和域,这能在编写时简化程序,在这个过程中常会用到关键字super。在完成最后两个实验时,我通过查书查资料,并仿照老师的源程序,写出了大概的程序,尤其是第二个程序,和之前的实验有相似之处。通过完成这次实验,我深深认识到,很多知识一定要看书,并多敲代码练习。而对于很多自己还不理解的知识,我也一定会加强学习,希望之后的实验中,遇到的问题能够越来越少。

猜你喜欢

转载自www.cnblogs.com/dhlll/p/9750213.html