微信

使用微信服务,更方便

职友集>Java面试题 > 请用Java代码解释一下什么是多态

请用Java代码解释一下什么是多态

2015-07-13 06:30:01 阅读( 254 )

2302人 收藏本页

标签:Java面试题

public class Farmyard
{
public static void main(String[] args)
{
Animal[] theYard = { new Cat(), new Dog(), new Cow(), new Pig(), new Mouse() };

Animal currentAnimal;

//get a random number generator
Random rng = new Random();

//make 10 random choices of Animal
for (int i = 0; i < 10; i++)
{
currentAnimal = theYard[rng.nextInt(theYard.length)];
System.out.println(currentAnimal.getType() + ” ” + currentAnimal.speak());
}
}
}
/***********************************************************************************
*/

abstract class Animal
{
private String type;

public Animal(String type)
{
this.type = type;
}

public String getType()
{
return type;
}

public abstract String speak();
}

/************************************************************************************
*/
class Cat extends Animal
{
public Cat()
{
super(“Cat”);
}

public String speak()
{
return (“Miaow”);
}
}

class Mouse extends Animal
{
public Mouse()
{
super(“Mouse”);
}

public String speak()
{
return (“Squeak”);
}
}

class Pig extends Animal
{
public Pig()
{
super(“Pig”);
}

public String speak()
{
return (“Grunt”);
}
}

class Cow extends Animal
{
public Cow()
{
super(“Cow”);
}

public String speak()
{
return (“Moo”);
}
}

class Dog extends Animal
{
public Dog()
{
super(“Dog”);
}

public String speak()
{
return (“Woof”);
}
}

来自IT公司面试手册

下一篇:java计时器:timer和timertask

上一篇:Java笔试基础题

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题