专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 一文读懂什么是Java多态性

一文读懂什么是Java多态性

更新时间:2022-09-27 11:08:08 来源:星辉 浏览1095次

Java多态是什么?多态意味着“多种形式”,当我们有许多通过继承相互关联的类时就会发生这种情况。

就像我们在上一章中指定的那样; 继承让我们从另一个类继承属性和方法。多态性使用这些方法来执行不同的任务。这使我们能够以不同的方式执行单个操作。

例如,考虑一个名为的超类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");
  }
}

现在我们可以创建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();
  }
}

以上就是关于“一文读懂什么是Java多态性”的介绍,大家如果想了解更多相关知识,不妨来关注一下星辉的Java教程,里面有更多的知识等着大家去学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>