水果机(java实现)java多态性

来源:互联网 发布:淘宝营销思路 编辑:程序博客网 时间:2024/04/28 08:45
import java.util.Random;
class afruit {
String  colour;

void eat() {

}

}

//abstract class afruit {
// String  colour;
//
// //abstract void show();
//
// void eat(){
//
// System.out.println("afruit.eat()");
// }
//
//}

interface  bfruit {
String colour = "bule";
void eat();


}

class cfruit extends afruit implements bfruit {
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("cfruit.eat()");
System.out.println("bfruit.eat");

}

}

class apple extends afruit {

void eat(){
colour = "red";
System.out.println("apple.eat()");
System.out.println(colour);
}
}
class pear extends afruit {

void eat() {
colour = "greend";
System.out.println("pear.eat()");
System.out.println(colour);
}
}

public class fruit {

static afruit eat(){
Random rand = new Random();
int x = rand.nextInt() % 3;

switch (x) {
case 0:
return new apple();
case 1:
return new cfruit();
default:
return new pear();
}
}

static void show(afruit a) {
a.eat();
}

public static void main(String[] args) {

// afruit a = new apple();
afruit a = eat();

show(a);
}
}
原创粉丝点击