Niqiqo
灰常可爱(*¥*)www.netube.cn

实验六继承定义与使用

实验时间 2018-9-28

1、实验目的与要求

(1) 理解继承的定义;

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

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

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

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

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

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

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

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

  • abstract类总结:
  • 在使用抽象类时需要注意几点:
    1、抽象类不能被实例化,实例化的工作应该交由它的子类来完成,它只需要有一个引用即可。
    2、抽象方法必须由子类来进行重写。
    3、只要包含一个抽象方法的抽象类,该方法必须要定义成抽象类,不管是否还包含有其他方法。
    4、抽象类中可以包含具体的方法,当然也可以不包含抽象方法。
    5、子类中的抽象方法不能与父类的抽象方法同名。
    6、abstract不能与final并列修饰同一个类。
    7、abstract 不能与private、static、final或native并列修饰同一个方法

     

  • 抽象类自身不能创建对象,但是它的子类可以创建对象。
    抽象它的关键字是abstract
    在父类中定义的抽象方法,在子类中必须实现(即方法重写)
    抽象方法没有方法体。
    抽象方法必须定义在抽象类中。
  • .继承中的this和super:

    构造器中的this表示当前正在初始化的对象引用,方法中的this表示当前正在调用此方法的对象引用。this具体用法表现在一下几个方面:

    1.当具多个重载的构造器时,且一个构造器需要调用另外一个构造其,在其第一行使用this( )形式调用,且只能在第一行;

    2.当对象中一个方法需要调用本对象中其他方法时,使用this作为主调,也可以不写,实际上默认就是this作为主调;

    3.当对象属性和方法中的局部变量名称相同时,在该方法中需要显式的使用this作为主调,以表示对象的属性,若不存在此问题,可以不显式的写this。

    其实,其牵涉到的一个问题就是变量的查找规则:先局部变量 => 当前类中定义的变量 => 其父类中定义的可以被子类继承的变量 => 父类...

    super表示调用父类中相应的属性和方法。在方法中,若需要调用父类的方法时,也一定要写在第一行

  • 构造器

  1. 子类是不能够继承父类的构造器,但是要注意的是,如果父类的构造器都是带有参数的,则必须在子类的构造器中显示地通过super关键字调用父类的构造器并配以适当的参数列表。如果父类有无参构造器,则在子类的构造器中用super关键字调用父类构造器不是必须的,如果没有使用super关键字,系统会自动调用父类的无参构造器。 

  •  重载方法
  1. 不能以返回值区分重载方法,而只能以“参数类型”和“类名”来区分
  • 重写
  1. 父类与子类之间的多态性,对父类的函数进行重新定义。如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。在Java中,子类可继承父类中的方法,而不需要重新编写相同的方法。
  2. 但有时子类并不想原封不动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。
  3. 方法重写又称方法覆盖。
  4.     (1)若子类中的方法与父类中的某一方法具有相同的方法名、返回类型和参数表,则新方法将覆盖原有的方法。

    如需父类中原有的方法,可使用super关键字,该关键字引用了当前类的父类

    (2)子类函数的访问修饰权限不能少于父类的;
    总之 :

    多态性是面向对象编程的一种特性,和方法无关,
        简单说,就是同样的一个方法能够根据输入数据的不同,做出不同的处理,即方法的
        重载——有不同的参数列表(静态多态性)

      而当子类继承自父类的相同方法,输入数据一样,但要做出有别于父类的响应时,你就要覆盖父类方法,

        即在子类中重写该方法——相同参数,不同实现(动态多态性)

     

      

 

2、实验内容和步骤

实验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;
      salary += raise;
   }
}
package inheritance;

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);//super提供对父类的访问。
      bonus = 0;
   }

    public double getSalary()//重写父类中定义的getSalary()
   {
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double b)
   {
      bonus = 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);
      boss.setBonus(5000);//更改Bonus值

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

      // print out information about all Employee objects
      for (Employee e : staff)
         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;

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

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;

      // must return false if the explicit parameter is null
      if (otherObject == null) return 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;

/**
 * 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);//用boss对象更改父类的Bonus初始值
      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
{
   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 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)
   {
      // 用 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)
         e.raiseSalary(5);//用e引用每个对象的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

 

package shape;
import java.math.*;
import shape.Circle;
import shape.Rectangle;
import java.util.Scanner;

public   class shape {//因为抽象类不能构造方法
	
	double PI =3.14;
	  double getPerimeter() {
		return 0;
	} //求解周长的方法
	 double getArea() {
		return 0;
	} //与求周长相同此时不能定义成public
	 public static void main(String[] args) {
		  Scanner in = new Scanner(System.in);
		  int n = in.nextInt();
		 System.out.println(" ");
		  String rect="rect";
		        String cir="cir";
		  shape[] A= new shape[n];
		 
		  for(int i=0;i<n;i++){
		   String s=in.next();
		   if(s.equals(rect)) {
			   
		  int length = in.nextInt();
		   int width = in.nextInt();
		   A[i]=new Rectangle(width,length);
		  
		     
		   }
		   
		         if (s.equals(cir)) {
		        
		      int radius = in.nextInt();
		      A[i]=new Circle(radius);
		     
		      
		         
		         }
		  }

		         shape c=new shape();
		         
		         
				System.out.println( c.sumAllPerimeter(A));
		         System.out.println(c.sumAllArea(A));
		  
		         for(int i=0;i<n;i++)
		         {
		             System.out.println(A[i]);
		             
		         }
		  
		         for(shape s:A) {
		             System.out.println(s.getClass()+","+s.getClass().getSuperclass());
		         
		  }
		  
	
	 }
		         
		           public double sumAllArea(shape B[])
		           {
		           double sum=0;
		           for(int i=0;i<B.length;i++)
		               sum+= B[i].getArea();
		               return sum;
		           }
		           public double sumAllPerimeter(shape B[])
		           {
		           double sum=0;
		           for(int i=0;i<B.length;i++)
		               sum+= B[i].getPerimeter();
		               return sum;
		           }    
		}
	
	

	

  

package shape;

public class Circle extends shape{ 
	private int radius;
	
	public Circle(int r) {
	    this.radius= r;
	}
	//继承父类
	double getPerimeter(){ //调用父类求周长的方法
	return 2*PI*radius;
	}
	double getArea(){
	return PI*radius*radius; //调用父类求面积的方法
	}
	 public String toString()
	    {
	          return  getClass().getName() + "[radius=" + radius + "]";
	    }
}

  

package shape;



public class Rectangle extends shape{ 
	private int length;
	private int width;
	public Rectangle(int length, int width) {//这地方的参数只是形参可以不和父类的实参相同
	    this.length = length;
	    this.width = width;
	}
	//继承父类
	public double getPerimeter() {//此时不能用abstract
		return 2*(length+width);
	}
	double getArea(){
	return length*width; //调用父类求面积的方法
	}
	public String toString()
    {
          return getClass().getName() + "[ width=" +  width + "]"+ "[length=" + length + "]";
    }
	}

  

 

实验3编程练习2

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

	 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 Demo {
	      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("D:/身份证号.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;

	         }
	  }
	   

  

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 ;
    }
}
	/*public void setStudentId(String string) {
		// TODO Auto-generated method stub
		
	}
	public int getStudentId() {
		// TODO Auto-generated method stub
		return 0;
	}


}*/

  

总结:在抽象类里面定义动态数组,并且引用父类的属性与方法,通过在子类当中实现该方法,这过程我还没有完全掌握,我想不用数组,临时定义一个变量通过不同的参数来引用子类的public方法,,,,可是还不能很好地实现,也许我理解有问题,还需要多查资料解决疑惑。。。。

posted on 2018-10-07 15:20  梓颜  阅读(253)  评论(0编辑  收藏  举报