更新時(shí)間:2020-06-17 14:57:41 來源:動(dòng)力節(jié)點(diǎn) 瀏覽3199次
面向?qū)ο蠡A(chǔ)
1、定義一個(gè)點(diǎn)類Point,包含2個(gè)成員變量x、y分別表示x和y坐標(biāo),2個(gè)構(gòu)造器Point()和Point(int x0,y0),以及一個(gè)movePoint(int dx,int dy)方法實(shí)現(xiàn)點(diǎn)的位置移動(dòng),創(chuàng)建兩個(gè)Point對(duì)象p1、p2,分別調(diào)用movePoint方法后,打印p1和p2的坐標(biāo)。
代碼演示
public?class?Point?{
//成員變量
private?double?x;
private?double?y;
//每一個(gè)類都帶有一個(gè)默認(rèn)的無參構(gòu)造函數(shù)
public?Point()?{
super();?//表示父類的構(gòu)造函數(shù)
/*
?*? 1.構(gòu)造函數(shù)與類名完全一致
?*? 2.不能帶有返回值類型
?*? 3.不需要return語句
?*?
?*? 作用:創(chuàng)建對(duì)象
?*/
}
public?Point(int?x0,int?y0)?{
this.x=x0;
this.y=y0;
}
public?void?movePoint(int?dx,int?dy)?{
this.x+=dx;
this.y+=dy;
}
public?static?void?main(String[]?args)?{
Point?p1?=?new?Point?(2,4);
p1.movePoint(2,?4);
System.out.println("p1坐標(biāo)為:"+p1.x+","+p1.y);
Point?p2?=?new?Point?(5,8);
p2.movePoint(50,?120);
System.out.println("p2坐標(biāo)為:"+p2.x+","+p2.y);
}
2、定義一個(gè)矩形類Rectangle:
2.1定義三個(gè)方法:getArea()求面積、getPer()求周長,showAll()分別在控制臺(tái)輸出長、寬、面積、周長。
2.2有2個(gè)屬性:長length、寬width
2.3通過構(gòu)造方法Rectangle(int width,int length),分別給兩個(gè)屬性賦值
2.4創(chuàng)建一個(gè)Rectangle對(duì)象,并輸出相關(guān)信息
代碼演示
public?class?Rectangle?{
int?length;
int?width;
/*
?*? static
?*? 1.修飾變量:直接通過類名來訪問
?*? 2.修飾方法:也可以通過類名來訪問
?*? 3.修飾代碼塊:加載類的時(shí)候優(yōu)先執(zhí)行,并只執(zhí)行一次
?*?
?*? 非靜態(tài)方法可以訪問靜態(tài)方法和變量
?*? 靜態(tài)方法不可以訪問非靜態(tài)方法和變量
?*/
public?int?getArea()?{
int?area=length*width;
return?area;
}
public?int?getPer()?{
return?(length+width)*2;
}
public?void?showAll()?{
int?l=this.length;
int?w=this.width;
int?a=length*width;
int?p=(length+width)*2;
System.out.println("長:"+l+","+"寬:"+w+","+"面積:"+a+","+"周長:"+p);
}
public?Rectangle?(int?length,int?width)?{
this.length=length;
this.width=width;
}
public?static?void?main(String[]?args)?{
Rectangle?r=new?Rectangle(5,5);
r.showAll();
}
設(shè)計(jì)一個(gè)類Student,該類包括姓名、學(xué)號(hào)和成績。設(shè)計(jì)一個(gè)方法,按照成績從高到低的順序輸出姓名、學(xué)號(hào)和成績信息。
代碼演示
public?class?Student?{
String?name;
int?empno;
int?grade;
public?Student(String?name,int?empno,int?grade)?{
this.name=name;
this.empno=empno;
this.grade=grade;
}
public?static?void?sort(Student[]?s)?{
for(int?i=1;i<s.length;i++)?{
for(int?j=0;j<s.length-i;j++)?{
if(s[j].grade?<?s[j+1].grade)?{
Student?t;
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
}
public?static?void?main(String[]?args)?{
Student?s1=new?Student("小明",?1,?80);
Student?s2=new?Student("小紅",?2,?90);
Student?s3=new?Student("小王",?3,?99);
Student[]?arr?=?{s1,s2,s3};
sort(arr);
for(Student?is:arr)?{
System.out.println(is.name+"\t"+is.empno+"\t"+is.grade);
}
}
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java面向?qū)ο缶毩?xí)題及答案”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)