您当前的位置: 首页 >  Java

川川菜鸟

暂无认证

  • 1浏览

    0关注

    969博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java多态性

川川菜鸟 发布时间:2021-11-03 02:04:46 ,浏览量:1

文章目录
    • 多态性

多态性

继承让我们从另一个类继承属性和方法。多态 使用这些方法来执行不同的任务。这允许我们以不同的方式执行单个操作。 举个例子:考虑一个名为 的超类Animal,它有一个名为 的方法animalSound()。Animals 的子类可以是 Pigs、Cats、Dogs、Birds - 而且它们也有自己的动物声音实现(猪的 oinks 和 cat meows 等):

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

前面我们使用extends关键字从类继承。 现在我们可以创建Pig和 Dog对象并调用它们的animalSound()方法:

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

运行: 在这里插入图片描述

关注
打赏
1665165634
查看更多评论
立即登录/注册

微信扫码登录

0.1268s