实验六 继承定义与使用

实验六 继承定义与使用

实验时间 2018-9-28

1、实验目的与要求

(1) 理解继承的定义;

继承已存在的类就是复用(继承)这些类的方法和域。在此基础上,还可以添加一些新的方法和域,以满足新的需求。这是Java设计程序中的一项核心技术。

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

继承在本职上是特殊一般的关系,即常说的is-a的关系。子类继承父类,表明子类是一种特殊的父类,并且具有父类所不具有的一些属性和方法。

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

Java继承的语法格式:

class  新类名  extends  已有类名 {...}

已有类名称为:超类,基类

新类称作:子类,派生类,或 孩子类

一般来说,子类比超类拥有的功能更加丰富。

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

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

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

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

为提高程序的清晰度,包含一个或多个抽象方法的类本身必须被声明为抽象类。

抽象类不能被实例化,即不能创建对象,只能产生子类。可以创建抽象类的对象变量,只是这个变量必须指向他的非抽象子类。

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

private:只有该类可以访问

Public:该类或非该类均可访问

Protected:该类及其子类的成员可以访问,同一个包中的类也可访问。

默认:相同包中的类可以访问。

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

Object类是java中所有类的祖先,每一个类都由它扩展而来,在不给出超类的情况下,java会自动把Object作为要定义类的超类。

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

ArrayList是一个采用类型参数的泛类型。为指定数组列表保存元素的对象类型,需要用一对尖括号将数组元素对象类名括起来加在后面。

ArrayList的定义

ArrayList <T> 对象 = new ArrayList<T> ();

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

声明枚举类:

Public enum Grade {A, B, C, D, E};

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

枚举类型是一个类,它的隐含超类是java.long.Enum

在比较两个枚举类型的值时,永远不要调用equals方法,直接使用“==”进行相等比较。

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)//构造器,构造管理者对象
   {
      // construct a Manager object
      Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);//生成Manger类对象,对象名为boss
      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);

      // print out information about all Employee objects
      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();//基本工资由父类getSalary获得
      return baseSalary + bonus;
   }

   public void setBonus(double b)//更改器
   {
      bonus = b;
   }
}

程序运行结果:

测试程序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());
// p.getDescription()    由于不能构造抽象类Person的对象,所以变量p永远不会引用Person对象,而Employee或Student这样的具体子类对象中都定义了getDescription方法
   }
}
package abstractClasses;

public abstract class Person//,为了提高程序的清晰度,包含一个或多个抽象方法的类必须被声明为抽象的
{
   public abstract String getDescription();//abstract方法,只能声明,不能实现
   private String name;

   public Person(String name)//构造器。为子类构造器提供服务   
   {
      this.name = name;
   }

   public String getName()
   {
      return name;
   }
}
package abstractClasses;

import java.time.*;//为第15行LocalDate方法提供服务

public class Employee extends Person
{
   private double salary;//private:仅对本类可见
   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);
      //String.format() :用于创建格式化的字符串以及连接多个字符串对象
   }

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

//定义一个扩展抽象类Person的具体子类Student,这个类不是抽象类
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;//this指代当前对象
   }

   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指代当前对象
      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)
   //Objects类中的equals方法用于检测一个对象是否等于另外一个对象
   {
      // a quick test to see if the objects are identical
      if (this == otherObject) return true;

      // must return false if the explicit parameter is null 如果显示参数为空,则返回false
      if (otherObject == null) return false;

      // if the classes don't match, they can't be equal
      if (getClass() != otherObject.getClass()) return false;
//getClass方法将返回一个对象所属的类
      // 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); 
      //Objects.hash()  这个类用于操作对象的静态实用方法这些工具包括用于计算对象的哈希代码的空安全或空容错方法,返回一个对象的字符串,并比较两个对象
      //Object类中的hashCode方法导出某个对象的散列码。散列码世人以整数,表示对象的存储地址
      //两个相等对象的散列码相等
   }

   public String toString()
   //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; 
      //在子类中定义equals 方法时,首先调用超类的equals,如果检测失败,对象就不可能像等,如果超类中的域都相等,就需要比较子类中的实例域
      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 + "]";
   }
}

 

测试程序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)
   {
      // 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%
      for (Employee e : staff)//使用for each循环遍历数组列表
         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);
      //valueOf方法用于返回相关Number对象持有传递的参数的值,该参数可以是基本数据类型,字符串等等
      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())。

Ÿ RectangleCircle继承自Shape类。

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

Ÿ main方法中

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

思考sumAllAreasumAllPerimeter方法放在哪个类中更合适?

输入样例:

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

shape

package shape;

abstract class Shape { 
abstract double getPerimeter(); 
abstract double getArea(); 
}

class Rectangle extends Shape{ 
private int length;
private int width;
public Rectangle(int length, int width) {
    this.length = length;
    this.width = width;
}

double getPerimeter(){ 
return 2*(length+width);
}
double getArea(){
return length*width; 
}
}

class Circle extends Shape{
private int radius;
public Circle(int radius) {
    this.radius = radius;
}
double getPerimeter(){
return 2 * Math.PI * radius;
}
double getArea(){
return Math.PI * radius * radius;
}
}

text

package shape;
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:"+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 小陈9;

import java.io.BufferedReader;
  import java.io.File;
  import java.io.FileReader;
 import java.io.IOException;
import java.util.ArrayList;
 import java.util.Scanner;
  
 public class Identity {
     private static ArrayList<Student>studentlist  = null;
     public static void main(String args[]) {
    
         studentlist = new ArrayList<>();
         Scanner scanner = new Scanner(System.in);
         File file = new File("c:/身份证号.txt" ); 
         BufferedReader reader = null; 
         try { 
             reader = new BufferedReader(new FileReader(file)); 
          
             String temp = null; 
             while ((temp = reader.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 province =linescanner.nextLine();
                  
                   Student student = new Student();
                   student.setName(name);
                   student.setnumber(number);
                   student.setsex(sex);
                   student.setage(age);
                   student.setprovince(province);
                   studentlist.add(student);
                      
                }
               
             reader.close(); 
         } catch (IOException e) { //读错
            e.printStackTrace(); 
        }
          
      
        int status=1;
           while (status!=0)
              {
                  
                 System.out.println("1:通过姓名查询");
                 System.out.println("2:通过身份证号查询");
                System.out.println("0:退出");
                
                 status = scanner.nextInt();
                switch (status) {
                 
                 case 1:             
                     System.out.println("请输入姓名:");
                    String scanner1 = scanner.next();
                     
                     int nameint = findStudentByName(scanner1);
                     if(nameint != -1) {
                       System.out.println("查找信息为:身份证号:"
                               + studentlist.get(nameint).getnumber() + "    姓名:"
                               + studentlist.get(nameint).getName() +"    性别:"
                               +studentlist.get(nameint).getsex()   +"    年龄:"
                               +studentlist.get(nameint).getage()+"  地址:"
                               +studentlist.get(nameint).getprovince()
                               );
 
                      
                     } break;
                 case 2:
                     System.out.println("请输入身份证号:");
                   
                     String studentid = scanner.next();
                     int id = findStudentById(studentid);
                   if (id != -1) {
                       System.out.println("查找信息为:身份证号:"
                               + studentlist.get(id ).getnumber() + "    姓名:"
                               + studentlist.get(id ).getName() +"    性别:"
                               +studentlist.get(id ).getsex()   +"    年龄:"
                               +studentlist.get(id ).getage()+"   地址:"
                               +studentlist.get(id ).getprovince()
                               );
 
                     
                }break;
                 
                 case 0:
                     status = 0;
                     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 小陈9;

public class Student {
    private String name;
    private    String number ;
    private    String sex ;
    private    String age;
    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 getage() {
        return age;
    }
    public void setage(String age ) {
        this.age=age ;
    }
    public String getprovince() {
        return province;
    }
    public void setprovince(String province) {
        this.province=province ;
    }
}

运行结果:

 

 总结:本周主要学习了对象与类,继承的概念。大量使用了访问器和更改器。了解到继承的优点是把所有子类的公共部分都放在了父类,使得代码得到了共享,可以避免重复,减少出错;可以轻松的定义子类;设计应用程序变得更加简单。对抽象类方面的知识没有完全了解,还需要继续学习。

 

转载于:https://www.cnblogs.com/980303CYR/p/9749831.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值