JAVA学习笔记(五)继承时的构造方法、多态、接口、汉诺塔

//:Cartoon.java
package com.junjun.java.test;

class Art {
	Art() {
		System.out.println("Art constructor");
	}
}

class Drawing extends Art {
	Drawing() {
		System.out.println("Drawing constructor");
	}
}

public class Cartoon extends Drawing {
	Cartoon() {
		System.out.println("Cartoon constructor");
	}
	
	public static void main(String[] args) {
		Cartoon x = new Cartoon();
	}
}

运行结果:

Art constructor
Drawing constructor
Cartoon constructor

//:Shapes.java
package com.junjun.java.test;

class Shape {
	void draw() {
		System.out.println(this + ".draw()");
	}
}

class Circle extends Shape {
	public String toString() {
		return "Circle";
	}
}

class Square extends Shape {
	public String toString() {
		return "Sauqre";
	}
}

class Triangle extends Shape {
	public String toString() {
		return "Trangle";
	}
}

public class Shapes {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//Object数组
		Object[] shapeList = {
				new Circle(),
				new Square(),
				new Triangle()
		};
		
		for(int i=0;i<shapeList.length;i++) {
			((Shape)shapeList[i]).draw();//需要强制转换类型
		}

	}

}


运行结果:

Circle.draw()
Sauqre.draw()
Trangle.draw()

//:Adventure.java
package com.junjun.java.test;

interface CanFight {
	void fight();
}

interface CanSwim {
	void swim();
}

interface CanFly {
	void fly();
}

class ActionCharacter {
	public void fight() {
		
	}
}

class Hero extends ActionCharacter implements CanFight,CanSwim,CanFly {
	public void swim() {}
	public void fly() {}
}

public class Adventure {
	public static void t(CanFight x) {
		x.fight();
	}
	public static void u(CanSwim x) {
		x.swim();
	}
	public static void v(CanFly x) {
		x.fly();
	}
	public static void w(ActionCharacter x) {
		x.fight();
	}
	public static void mian(String[] args) {
		Hero h = new Hero();
		t(h);//把h当做CanFight
		u(h);//把h当做CanSwim
		v(h);//把h当做CanFly
		w(h);//把h当做ActionCharacter
	}
}


 

//:HaioTower
public class HaioTower {
	//将n个盘从form柱移到to柱,以aux柱为辅助柱
	public static void move(int n,char from,char to,char aux) {
		if(n==1) {
			//仅有一个盘时,直接从from柱移到to柱
			System.out.println("将#1盘从 " + from + " 移到 " +to);
		}else {
			//将n-1个盘从from柱移到aux柱,以to柱为辅助柱
			move(n-1,from,aux,to);
			//将最下面的圆盘从from柱移到to柱
			System.out.println("将#" + n + "盘从 " + from + " 移到 " + to);
			//将n-1个盘从aux柱移到to柱,以from柱为辅助柱
			move(n-1,aux,to,from);
		}
	}
	
	public static void main(String[] args) {
		//将3个圆盘从A柱移到C柱,移动时利用B柱为辅助柱
		move(3,'A','C','B');
	}
}


运行结果:

将#1盘从 A 移到 C
将#2盘从 A 移到 B
将#1盘从 C 移到 B
将#3盘从 A 移到 C
将#1盘从 B 移到 A
将#2盘从 B 移到 C
将#1盘从 A 移到 C

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值