//: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