实验五 接口与包

更新时间:2024-04-19 23:11:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

《Java语言程序设计》实验报告

实验名称 姓名 专业 学号 班级 实验五 接口与包 成绩 日期 (1)掌握接口和的实现和使用方法。 实验 目的 (2)了解内部类的实现原理。 (3)理解包的概念和作用,掌握包的编写以及如何使用包中的类。 实验 本次共有 2 个练习,完成 2 个。 进度 本次实验的步骤或程序及运行结果(表格不够可另加附页)。 (1)定义一个接口Area,其中包含一个计算面积的抽象方法calculateArea(),然后分别设计MyCircle和MyRectangle两个类都实现这个接口中的方法calcualteArea(),分别计算圆的面积和矩形的面积。 实 验 内 容 代码: package exp5; public interface Area { public abstract double calculateArea(); } package exp5; public class MyRectangle implements Area { protected double a; protected double b; public MyRectangle(double a,double b) { this.a=a; this.b=b; } public double calculateArea() { return this.a*this.b;

}

public String toSting() {

return \该矩形长为:\+a+\,宽为:\+b+\,面积为:\+calculateArea(); }

public static void main(String args[]) { }

System.out.println(new MyRectangle(25,4).toSting()); }

运行结果:

代码:

package exp5;

public class MyCircle implements Area {

protected double r; public MyCircle(double r) {

this.r = r; }

public double calculateArea() {

return Math.PI*this.r*this.r; }

public String toSting() {

return \该圆形半径为:\+r+\,面积为:\+calculateArea(); }

public static void main(String args[]) {

System.out.println(new MyCircle(10).toSting()); } }

运行结果:

(2)定义一个外部类Outer,包含属性姓名name和方法getInfo( ),在getInfo( )方法中包含两

个属性年龄age和性别sex,并定义一个内部类Inner,在Inner内有sayHello( )方法,在sayHello()方法中输出姓名、年龄和性别的信息。

代码:

package exp5;

import java.util.Scanner; public class Outer {

protected Inner charater; protected String name; protected int age; protected String sex; public void getInfo() {

Scanner sc = new Scanner(System.in); System.out.print(\年龄:\); int age = sc.nextInt(); System.out.print(\性别:\); String sex = sc.next(); this.age = age; this.sex = sex; sc.close(); }

private class Inner {

//Outer.Inner p = new Inner(); void sayHello() { } }

public Outer(String name) {

this.name = name; this.getInfo();

this.charater = new Inner(); }

public static void main(String [] args) {

Outer p = new Outer(\); p.charater.sayHello(); } }

System.out.println(\姓名:\+name+\,年龄:\+age+\,性别:\+sex);

实 验 内 容

运行结果:

本次试验运行情况良好。通过本次试验我掌握接口和的实现和使用方法、了解内部类的实现原理、理解了包的概念和作用,掌握了包的编写以及如何使用包中的类,进一步锻炼了我的编程能力。

实验 分析

本文来源:https://www.bwwdw.com/article/gcvp.html

Top