`
xitong
  • 浏览: 6178818 次
文章分类
社区版块
存档分类
最新评论

java 类的学习——多态

 
阅读更多

1.多态性:访问子类可以通过访问父类:

Animal cat =new Cat();

Animal dog =new Dog();

2.在使用多态的时候,如果有使用覆盖函数,那么被覆盖的方法(即是父类中的的那个相应的方法)是要存在的。

3. 多态:一个引用(类型)在不同情况下的多种状态,可使代码更加灵活

4.java允许父类的引用变量引用它子类的实例,是自动完成的

代码:

package com.agui;

public class Demo5 {


public static void main(String[] args) {
// TODO Auto-generated method stub
Dog2 ddd=new Dog2();
ddd.cry();
Cat2 ccc=new Cat2();
ccc.cry();
Animal2 an =new Cat2();
an.cry();
Master xxx=new Master();
xxx.feed(new Dog2(),new Bone());
}

}


//动物类
class Animal2
{
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

//叫
public void cry()
{
System.out.println("buxiaodezenmejiao");

}
public void eat()
{

System.out.println("buzhidao chishenme");

}
}

class Master
{
//使用多态,方法就可以用一个了

public void feed(Animal2 an,Food f)
{
an.eat();
f.showName();
}
}


class Food
{
String name;
public void showName()
{

}
}

class Fish extends Food
{
public void showName()
{
System.out.println("yurou");

}

}
class Bone extends Food
{
public void showName()
{
System.out.println("gutou");

}

}


class Cat2 extends Animal2
{
//猫自己叫
public void cry()
{
System.out.println("maomaojiao");
}
public void eat()
{
System.out.println("aichiyu");
}

}


class Dog2 extends Animal2
{
//gou自己叫
public void cry()
{
System.out.println("wangwangjiao");
}
public void eat()
{

System.out.println("aichigutou");

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics