Java 实验一
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package shiyan1;
publicclass Rectangle {
privatedouble width;
privatedouble height;
private String colour;
publicdouble getWidth() {
return width;
}
publicvoid setWidth(double width) {
this.width = width;
}
publicdouble getHeight() {
return height;
}
publicvoid setHeight(double height) {
this.height = height;
}
public String getColour() {
return colour;
}
publicvoid setColour(String colour) {
this.colour = colour;
}
public Rectangle(double width, double height, String colour) {
setWidth (width);
setHeight (height);
setColour (colour);
}
publicdouble getArea(double width, double height, String colour){ double area=0.0;
area=this.height*this.width;
return area;
}
public String toString(){
return"矩形的宽:"+width+"cm"+"\n"+"矩形的高:"+height+"cm"+"\n"+"矩形的颜色:"+colour;
}
publicstaticvoid main(String[] args) {
Rectangle rec= new Rectangle(3,4,"绿色");
System.out.println(rec.toString());
System.out.println("矩形的面积:" +rec.getArea(3,4,"绿色") +"cm^2");
}
复数:
package shiyan2;
publicclass Complex {
int x,y;
Complex(int i,int j){
x=i;
y=j;
}
publicvoid showComp(){
if(y>=0)
System.out.println(x+"+"+y+"i");
else
System.out.println(x+""+y+"i");
}
public Complex addComp(Complex C2){
returnnew Complex(this.x+C2.x,this.y+C2.y);
}
public Complex subComp(Complex C2){
returnnew Complex(this.x-C2.x,this.y-C2.y);
}
public Complex multiComp(Complex C2){
returnnew
Complex(this.x*C2.x-this.y*C2.y,this.x*C2.y+C2.x*this.y);
}
publicboolean equalComp(Complex C2){
returnthis.x==C2.x&&this.y==C2.y;
}
publicstaticvoid main(String args[]){
Complex c=new Complex(1,-2);
System.out.println("原复数:");
c.showComp();
System.out.println("相加:");
c.addComp(new Complex(3,-4)).showComp();
System.out.println("相减:");
c.subComp(new Complex(3,-4)).showComp();
System.out.println("相乘:");
c.multiComp(new Complex(3,-4)).showComp();
System.out.println("比较是否相等:"+c.equalComp( new Complex(1,-2)));
System.out.println("比较是否相等:"+c.equalComp( new
Complex(3,-3)));
}
}
package shiyan1;
publicclass My {
String s;
public My() {
s = "Constructor";
}
publicvoid go() {
System.out.println(s);
}
publicstaticvoid main(String args[]) { My m = new My();
m.go();
}
}
注意:public void My() {
s = "Constructor";
}
由于加了void所以my()不是构造方法,void要删除。
package shiyan1;
class Pet {
protected String name;
public Pet(String n) {
name = n;
}
public String getName() {
return name;
}
public String move() {
return"run";
}
public String speak() {
return"";
}
public String toString() {
return"My pet " + name;