西安财经学院信息学院
《Java程序设计》 实验报告
姓名 任超慧
学号 1105170103
班级 计本 1101
年级 11 级
指导教师 李翠
实验名称
类与对象
实验室 实验楼 501 实验日期 2013-4-22
一、实验目的
类与对象
1、 掌握类的定义和使用,编写构造方法及成员方法。
2、 能够创建类的实例,掌握对象的声明和不同访问属性的成员访问方式。
3、 会定义接口、实现接口。
二、实验内容
1. 设计并实现一个课程类,代表学校中的一门课程,将这门课程的相关信息组成该类的属性(如课程
代码、课程名称、课程类别、学时、学分等),并在类中定义各个属性相关的访问方法(如获取和
设置课程代码、课程名称,课程类别,获取和修改学时、学分,打印输出课程基本信息等),最后
使用主函数测试此类(包括创建对象,调用相应方法等)。
2. 在 java 中,定义一个接口,声明计算图形面积和周长的抽象方法,再用类去实现这个接口,再编写
一个测试类去使用这个接口。
三、实验环境
Eclipse环境
四、实验步骤
实验一:
源代码:
1、
class Course{
int Cnumber;
String Cname;
String Ctype;
int Ctime;
int Cscrose;
Course(int Cnu,String Cna,String Cty,int Ct,int Cs){
Cnumber=Cnu;
Cname=Cna;
Ctype=Cty;
Ctime=Ct;
Cscrose=Cs;
}
void display1(){
第 1 页 共 6 页
System.out.println("课程号:"+Cnumber);
}
void change1(int Cnu){
Cnumber=Cnu;
}
void display2(){
System.out.println("课程名称:"+Cname);
}
void change2(String Cna){
Cname=Cna;
}
void display3(){
System.out.println("课程类型:"+Ctype);
}
void change3(String Cty){
Ctype=Cty;
}
void display4(){
System.out.println("课时:"+Ctime);
}
void change4(int Ct){
Ctime=Ct;
}
void display5(){
System.out.println("课程学分:"+Cscrose);
}
void change5(int Cs){
Cscrose=Cs;
}
}
public class Lesson{
public static void main(String []args){
Course human=new Course(1,"English","必修",54,4);
human.display1();
human.display2();
第 2 页 共 6 页
human.display3();
human.display4();
human.display5();
human.Cnumber=2;
human.Cname=new String("Math");
human.Ctype=new String("必修");
human.Ctime=36;
human.Cscrose=5;
System.out.println("修改后的课程信息:");
human.display1();
human.display2();
human.display3();
human.display4();
human.display5();
}
}
实验二:
源代码:
2、
public class Client{
public static void main(String []args){
ICalculate cal=new Calculate();
MyRectangle rect=new MyRectangle(10,5);
System.out.println(rect+"周长为:"+cal.calcuGirth(rect));
System.out.println(rect+"面积为:"+cal.calcuArea(rect));
rect=new MyRectangle(30,50);
System.out.println(rect+"周长为:"+cal.calcuGirth(rect));
System.out.println(rect+"面积为:"+cal.calcuArea(rect));
}
}
interface ICalculate{
int calcuArea(MyRectangle rect);
int calcuGirth(MyRectangle rect);
}
class Calculate implements ICalculate{
//计算面积的方法
public
int calcuArea(MyRectangle rect){
int result=rect.getWidth()*rect.getHeight();
return result;
}
第 3 页 共 6 页
//计算周长的方法
public int calcuGirth(MyRectangle rect){
int result=(rect.getWidth()+rect.getHeight())*2;
return result;
}
}
class MyRectangle{
private int width;
private int height;
public MyRectangle(int width ,int height){
this.width=width;
this.height=height;
}
public int getWidth(){
return width;
}
public void setWidth(int width){
this.width=width;
}
public void setHeight(int height){
this.height=height;
}
public int getHeight(){
return height;
}
public String toString(){
return super.toString()+"[width="+width+",height="+height+"]";
}
}
五、实验结果
实验一:
第 4 页 共 6 页
实验二:
六、小结
通过本次实验,掌握了 JAVA 中类与对象的概念和基本定义方法,在试验过程中基本掌握
了类的定义和使用,编写构造方法及成员方法。能够创建类的实例,掌握对象的声明和不同访
问属性的成员访问方式。会定义接口、实现接口。发现了它比 C++面向对象的方法有了更进一
步的提升。
第 5 页 共 6 页
第 6 页 共 6 页