(1)定義閉合圖形抽象類ClosedFigure定義屬性:1.形狀;2.定義構造方法,給形狀賦值;3.定義兩個抽象方法:計算面積和計算周長;4.定義一個顯示方法:顯示圖像形狀,周長,面積;


題目顯示不全,完整題目描述:

(1)定義閉合圖形抽象類ClosedFigure定義屬性:1.形狀;2.定義構造方法,給形狀賦值;3.定義兩個抽象方法:計算面積和計算周長;4.定義一個顯示方法:顯示圖像形狀,周長,面積;(2)定義ClosedFigure的子類橢圓Ellipse定義屬性:1.長短軸定義構造方法:初始化長短軸;2.實現從父類繼承來的抽象方法;[提示:橢圓求周長公式Math.PI*(this.radius_a+this.radius_b)](3)定義ClosedFigure的子類矩形類Rectangle定義屬性:1.長和寬定義構造方法:初始化長和寬;2.實現從父類繼承來的抽象方法;

完整代碼如下:

package naizi;

import java.util.Scanner; 

//閉合圖形抽象類
abstract class ClosedFigure{

public String shape;

public ClosedFigure(String shape){
	this.shape=shape;
}

abstract double perimeter();
abstract double area();

public void print()               //顯示形狀、屬性、周長及面積 
{ 
    System.out.println("this is a "+this.shape+",perimeter:"+this.perimeter()+",area:"+this.area());
} 
}

//定義橢圓類  
class Ellipse extends ClosedFigure{


double Longaxis,Shortaxis;

public Ellipse(String shape) {
	super(shape);
}
public Ellipse(double a,double b) {
	this("Ellipse");
	this.Longaxis=a;
	this.Shortaxis=b;
}
double perimeter(){
	return Math.PI*(this.Longaxis+this.Shortaxis);
}
double area(){
	return Math.PI*this.Longaxis*this.Shortaxis;
}
}

//定義矩形類 
class Rectangle extends ClosedFigure{

double Length,Width;

public Rectangle(String shape) {
	super(shape);
}
public Rectangle(double a,double b) {
	this("Rectangle");
	this.Length=a;
	this.Width=b;
}
double perimeter(){
	return 2*(this.Length+this.Width);
}
double area(){
	return this.Length*this.Width;
}
}


public class ClosedFigure_ex
{ 
public static void main(String args[]){ 
	int a,b; 
	ClosedFigure d1; 
	ClosedFigure d2;
	
	try{ 
		Scanner sc = new Scanner(System.in); 
		String str1 = sc.next(); 
		a=Integer.parseInt(str1); 
		str1 = sc.next(); 
		b=Integer.parseInt(str1); 
		d1=new Ellipse(a,b); 
		d1.print(); 

		String str2 = sc.next(); 
		a=Integer.parseInt(str2); 
		str2 = sc.next(); 
		b=Integer.parseInt(str2); 
		d2=new Rectangle(a,b); 
		d2.print(); 
		} catch(Exception e){
			System.out.println("error"); 
			} 
} 
}

測試如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM