Java面向對象練習題及答案

Java面向對象練習題及答案

長沙達內教育      2022-03-18 23:20:01     9

Java面向對象練習題及答案,面向對象基礎1、定義一個點類Point,包含2個成員變量x、y分別表示x和y坐標,2個構造器Point()和Point(int x0,y0),以及一個movePo

課程價格 請咨詢

上課時段: 授課校區(qū):

詳細介紹

面向對象基礎

1、定義一個點類Point,包含2個成員變量x、y分別表示x和y坐標,2個構造器Point()和Point(int x0,y0),以及一個movePoint(int dx,int dy)方法實現點的位置移動,創(chuàng)建兩個Point對象p1、p2,分別調用movePoint方法后,打印p1和p2的坐標。

代碼演示

public?class?Point?{		//成員變量	private?double?x;	private?double?y;		//每一個類都帶有一個默認的無參構造函數	public?Point()?{		super();?//表示父類的構造函數					}	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坐標為:"+p1.x+","+p1.y);				Point?p2?=?new?Point?(5,8);		p2.movePoint(50,?120);		System.out.println("p2坐標為:"+p2.x+","+p2.y);	}

2、定義一個矩形類Rectangle:

2.1定義三個方法:getArea()求面積、getPer()求周長,showAll()分別在控制臺輸出長、寬、面積、周長。

2.2有2個屬性:長length、寬width

2.3通過構造方法Rectangle(int width,int length),分別給兩個屬性賦值

2.4創(chuàng)建一個Rectangle對象,并輸出相關信息

代碼演示

public?class?Rectangle?{	int?length;	int?width;				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();	}

設計一個類Student,該類包括姓名、學號和成績。設計一個方法,按照成績從高到低的順序輸出姓名、學號和成績信息。

代碼演示

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

以上就是長沙達內教育java培訓機構的小編針對“Java面向對象練習題及答案”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務。

培訓啦提醒您:交易時請核實對方資質,對于過大宣傳或承諾需謹慎!任何要求預付定金、匯款等方式均存在風險,謹防上當。