码迷,mamicode.com
首页 > 编程语言 > 详细

java 多态

时间:2019-03-29 17:24:42      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:cat   info   com   idt   图片   sed   feed   pac   hide   

案例一:

Animal:

技术图片
package text2;

public class Animal {
private String name;
private 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("不知道怎么叫");
    
}
}
View Code

Cat:

技术图片
package text2;

public class Cat extends Animal{
    
public void cry(){
    System.out.println("喵喵叫");
}
}
View Code

Dog;

技术图片
package text2;

public class Dog extends Animal{
public void cry(){
    System.out.println("汪汪叫");
}
}
View Code

Test:

技术图片
package text2;

public class Tset {
public static void main(String[] args){
    Cat cat=new Cat();
    cat.cry();
    Dog dog=new Dog();
    dog.cry();
    Animal an=new Cat();
    an.cry();
    an=new Dog();
    an.cry();
}
}
View Code

 

案例二;

技术图片

Animal:

技术图片
package text2;

public class Animal {
private String name;
private 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("不知道怎么叫");
    
}
public void eat(){
    
}
}
View Code

Cat;

技术图片
package text2;

public class Cat extends Animal{
    
public void cry(){
    System.out.println("喵喵叫");
}
public void eat(){
    System.out.println("猫喜欢吃鱼");
}
}
View Code

Dog:

技术图片
package text2;

public class Dog extends Animal{
public void cry(){
    System.out.println("汪汪叫");
}
public void eat(){
    System.out.println("狗喜欢吃骨头");
}
}
View Code

Food;

技术图片
package text2;

public class Food {
String name;
public void showname(){
    
}

}
View Code

Fish:

Bone;

技术图片
package text2;

public class Bone extends Food{
public void showname(){
System.out.println("我是骨头");    
}

}
View Code

MAster:

技术图片
package text2;

public class Master {
//给动物喂食物
    public void feed(Animal an,Food f)//灵活
        {
        an.eat();
        f.showname();
    }
    
}
View Code

Test;

技术图片
package text2;

public class Tset {
public static void main(String[] args){
    Master master=new Master();
    master.feed(new Dog(), new Bone());
    
}
}
View Code

 

java 多态

标签:cat   info   com   idt   图片   sed   feed   pac   hide   

原文地址:https://www.cnblogs.com/helloworld2019/p/10622555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!