201771010113 李婷华 《面向对象程序设计(Java)》第六周总结

一.理论知识部分

第四章 类与对象

1.方法的定义:方法声明和方法体。

2.重载:一个类中可以有多个方法具有相同的名字,不同的类型,不同的参数。

3.构造器:也叫构造方法,是类中的一种特殊的方法,其作用是用来构造并初始化对象。

4.构造器的名字必须与它所在的类名相同。每个类可以有一个以上的构造器。构造器可以有0个、1个或1个以上的参数。构造器没有返回值。构造器总是被new运算符调用。构造器可以调用另一个构造器。

5.类的访问权限:一个方法可以访问所属类的私有数据。

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

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

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

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

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

11.程序设计语言中将参数传递给方法的方式:(1)值调用(2)引用调用

12.一个方法可以修改传递引用所对应的变量值,而不能修改传递值调用所对应的变量值。

13.Java值调用:方法得到的是所有参数值的一个拷贝,方法不能修改传递给它的任何参数变量的内容。

14.Java中方法参数有两种类型:基本数据类型、对象。

15.一个方法不可能修改一个基本数据类型的参数。

16.Java中方法的对象参数采用的是值传递。

17.Java方法参数的使用:一个方法不能修改一个基本数据类型的参数。一个方法可以改变一个对象参数的状态。一个不能实现让对象参数引用一个新的对象。

18.对象的定义:对象的声明、创建对象。

19.类定义的变量中含有静态变量时,该类所有对象的静态变量共享同一存贮单元。

20.在类定义中,可以直接将一个常数赋给一个域。可调用方法对域进行初始化。

21.为实例域初始化的方法:(1)在构造器中设置值(2)声明的同时赋值(3)用初始化块

22.Java中常把多个类放在一起形成一个包。使用包的主要原因是确保类名的唯一性。

23.一个类可以直接使用它所在的包中的所有类,也可所有来自其他包中的所有public类。

24.访问其他包中的类的方式(1)类名前加上完整的包名(2)利用import语句导入特定的类。

25.import语句不仅可以导入类,还可以导入静态方法和静态域。

26.类中标记为public的部分可以被任意类使用。

27.类中标记为private的部分只能在类中使用。

第五章 继承

1.继承:用已有类来构造新类的一种机制。当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域。

2.继承的特点:具有层次结构、子类继承了父类的方法和域。

3.继承的优点:(1)代码可重用性(2)可以轻松定义子类(3)父类的域和方法可用于子类(4)设计应用程序变得更加简单

4.子类比超类拥有的功能更加丰富。

5.通过扩展超类来定义子类时,仅需要指出子类与超类的不同之处。

6.super是一个指示编译器调用超类方法的特有关键字。

7.super的用途:(1)调用超类的方法(2)调用超类的构造器

8.超类中的方法可在子类中进行方法重写。

9.可将子类对象赋给超类变量。

10.方法的名称和参数列表称为方法的签名。

11.不允许继承的类称为final类,在类的定义中用final修饰符加以说明。

12.把超类对象赋给子类对象变量,就必须进行强制类型转换。

子类  对象=(子类)(超类对象变量)

13.为了提高程序的清晰度,包含一个或多个抽象方法的类本身必须被声明为抽象类。除了抽象方法之外,抽象类还可以包含具体数据和具体方法。

14.抽象方法充当着占位的角色,他们的具体实现在子类中。

15.抽象类不能被实例化,即不能创建对象,只能产生子类。可以创建抽象类的对象变量。

二.实验部分

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类
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
      boss.setBonus(5000);//调用更改器

      Employee[] staff = new Employee[3];

      // fill the staff array with Manager and Employee objects

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

实验结果:

OO风格程序构造特点:继承的特点是具有层次结构,使程序的构造思路看上去一目了然。

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

      // 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)
         System.out.println(p.getName() + ", " + p.getDescription());
   }
}
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;

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

实验结果:

测试程序3:

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

掌握Object类的定义及用法;

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

代码:

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;

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;

      // 判断两个引用是否是同一个
      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
            + "]";
   }
}
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
{  
   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 Demo;

import Demo.Shape;
import Demo.Rectangle;
import Demo.Circle;
import java.math.*;
import java.util.Scanner;
public class demo {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println();
        int n=in.nextInt();
        String rect="rect";
        String cir="cir";
        Shape [] a=new Shape[n];
        for(int i=0;i<n;i++) {
            String read=in.next();
            if(read.equals(rect)) {
                int length=in.nextInt();
                int width=in.nextInt();
                a[i]=new Rectangle(width,length);
            }
            if(read.equals(cir)) {
                int radius=in.nextInt();
                a[i]=new Circle(radius);
            }
        }
        for(int i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
        
        demo b=new demo();
        System.out.println(b.sumAllPerimeter(a));
        System.out.println(b.sumAllArea(a));
        for(Shape s:a) {
            System.out.println(s.getClass()+","+s.getClass().getSuperclass());
        }
    }
    public double sumAllArea(Shape a[])
    {
        double sum=0;
        for(int i=0;i<a.length;i++)
            sum=sum+a[i].getArea();
            return sum;
    }
        public double sumAllPerimeter(Shape a[])
        {
            double sum=0;
            for(int i=0;i<a.length;i++)
            sum=sum+a[i].getPerimeter();
            return sum;
        }
    }
package Demo;
public abstract class Shape {
    double PI=3.14;
    public abstract double getPerimeter();
    public abstract double getArea();

}
package Demo;
public class Rectangle extends Shape{
    private int width;
    private int length;
    public Rectangle(int wid,int len)
    {
        this.width=wid;
        this.length=len;
    }
    public double getPerimeter()
    {
        return (width+length)*2;
    }
    public double getArea()
    {
        return width*length;
    }
    public double getWidth()
    {
        return width;
    }
    public double getLength()
    {
        return length;
    }
    public String toString()
    {
          return "Rectangle"+ "[ width=" +  width + ","+ "length=" + length + "]";
    }
}
package Demo;

public class Circle extends Shape{

    private int radius;
    public Circle(int r)
    {
        radius=r;
    }
    public double getPerimeter()
    {
        return 2*PI*radius;
    }
    public double getArea()
    {
        return PI*radius*radius;
    }

    public double getRadius()
    {
        return radius;
    }
    
    public String toString()
    {
          return  "Circle"+"["+"radius=" + radius + "]";
    }
       
}

实验结果:

实验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<Citizen> citizenlist;
    public static void main(String[] args) {
        citizenlist = 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();
                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;
    }   
}
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 ;
    }
}

实验结果:

3.总结:

通过本章的学习,我理解了父类和子类的定义,而继承指的是子类继承父类的方法和域,以便于简化程序,在这个过程中常会用到关键字super。我也学会了如何去定义一个抽象类。但是在写程序的过程中,仍然有问题存在,虽然写出了实验二的程序,可是输出的格式和题目所要求的还是有出入,目前为止,这个问题依然没有想到解决的办法。通过这几周的学习,我的编程能力较以前还是有很大的长进,学会了许多以前不知道的知识,学会了什么情况下用for,while,do-while循环。

猜你喜欢

转载自www.cnblogs.com/litinghua/p/9725244.html