demo.java

来自「java的书上例子」· Java 代码 · 共 75 行

JAVA
75
字号
/** 一个应用程序,用来演示abstract类和abstract方法 */

/** 抽象类Shape */
abstract class Shape{
	int position_x,position_y; //座标变量

	/** MoveTo()方法,移动座标到指定位置 */
	void MoveTo(int new_pos_x,int new_pos_y){ 
		position_x=new_pos_x;
		position_y=new_pos_y;
	}

	/** draw()方法,为抽象方法 */
	abstract void draw(); 
}//抽象类Shape结束

/** Square类,为Shape类的子类 */
class Square extends Shape{
	int length;

	/** 实现了父类的draw()方法 */
	void draw(){
		System.out.println("This is a square.");
     	//以(position_x,position_y)为中心,画出一个边长是length的正方形
	}
}//Square类结束

/** Circle类,为Shape类的子类 */
class Circle extends Shape{
	int radius;

	/** 实现了父类的draw()方法 */
	void draw(){
		System.out.println("This is a circle.");
     	//以(position_x,position_y)为中心,画出一个半径是radius的园
	}
}//Circle类结束

/** Trigon类,为Shape类的子类 */
class Trigon extends Shape{
	int bottom;
	int highness;

	/** 实现了父类的draw()方法 */
	void draw(){
	    System.out.println("This is a trigon.");
    	//以(position_x,position_y)为重心,画出一个
		//底为bottom,高为highness的三角形
	}
}//Trigon类结束

/** ShapeManager类 */
class ShapeManager{

	/** manager()方法 */
	void manager(Shape obj){ //该方法以Shape类型的对象为参数
		obj.draw();           //调用时,可以子类对象代替
	}
}//ShapeManager类结束

/** Demo类 */
public class Demo{

	/** main()方法 */
	public static void main(String args[]){
		ShapeManager shape_man=new ShapeManager();
		Square sq=new Square();
		Circle ci=new Circle();
     	Trigon tr=new Trigon();
		shape_man.manager(sq); //sq,ci,tr都是Shape类的子类对象
		shape_man.manager(ci);
     	shape_man.manager(tr);
	}
}//Demo类结束

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?