日期:2014-05-20 浏览次数:20915 次
class Apple {
Apple getPeeled() { return Peeler.peel(this); }
}
------解决方案--------------------
//这个类抽象的表示人
class Person {
//有eat方法,就是人可以吃,参数是类Apple,也就是这个人吃苹果
public void eat(Apple apple) {
//在吃之前要先得到削皮了的苹果
Apple peeled = apple.getPeeled();
//然后就是输出
System.out.println("Yummy");
}
}
//这个类抽象的表示一个削皮器
class Peeler {
//有个静态方法,也就是不用new这个对象,就可以调用此方法,即削皮
//参数是Apple苹果,其实最好在里面能处理下,把苹果中添加个是否削皮了的字段,
//调用过此方法后,把这个标志符成true
static Apple peel(Apple apple) {
//返回一个被削皮的苹果
return apple;
}
}
//抽象的表示苹果
class Apple {
//有了苹果,就可以得到削皮的苹果
//没有苹果,那么也就不能得到削皮的苹果
//所以这个方法不能是static的
//方法的实现是调用削皮器进行削皮,
//参数就是它自己(当前对象),也就是this,this就是苹果Apple类的对象。
Apple getPeeled() { return Peeler.peel(this); }
}
public class PassingThis {
public static void main(String args []) {
//生成一个人,去吃苹果
new Person().eat(new Apple());
}
}
------解决方案--------------------
火龙果正解..
------解决方案--------------------
搞了半天不就是做了Apple peeled =apple这句话嘛……被耍了。
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled(); //(3)调用apple.getPeeled方法,(5)将返回的apple对象的引用赋值给这个新的Apple对象 peeled
System.out.println("Yummy"); //(6)打印yummy
System.out.println(apple);
System.out.println(peeled);//(7)你打印出来看看,一样的。
}
}
class Peeler {
static Apple peel(Apple apple) {
return apple; //(5)返回apple对象
}
}
class Apple {
Apple getPeeled() { return Peeler.peel(this);} //(4)调用Peeler.peel方法,参数this就是这个apple对象
}
public class Poor {
public static void main(String args []) {
new Person().eat(new Apple()); //(1)new了个Apple对象,new了个Person对象(2)调用.eat方法
}
}
------解决方案--------------------
很有意思的代码,感觉Person被耍了,Peeler只是把得到的苹果原样返回了。
不过只要稍加扩展就可以,如:
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
if (peeled instanceof Peeler.PeeledApple)
System.out.println("Yummy");
else
throw new Peeler.UnpeeledException();
}
}
class Peeler {
// 削皮器自己管理一个“削了皮的苹果”类PeeledApple和一个UnpeeledException异常类
static class PeeledApple extends Apple {
PeeledApple(Apple apple) { }
}
static class UnpeeledException extends RuntimeException { }
static Apple peel(Apple apple) {
return new PeeledApple(apple);
}
}
class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
}
public class PassingThis {
public static void main(String args[]) {
new Person().eat(new Apple());
}
}
------解决方案--------------------
mark
------解决方案--------------------
看看..
------解决方案--------------------
学习中~~~
------解决方案--------------------
写这种程序的目的是啥啊? 锻炼思维? 有种故意把简单的问题弄复杂的感觉 , 哎 不过还是学习下
------解决方案--------------------