1.继承
Java多态的实现方式之一是继承。在继承的结构中,父类和子类之间存在着一种“is-a”的关系。父类可以定义有用的方法和属性,而子类则可以从父类继承这些方法和属性。当父类引用指向子类时,就会出现多态的情况。
例如:
class Animal{
public void eat(){
System.out.println("Animal is eating");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("Dog is barking and eating");
}
}
public class Test{
public static void main(String[] args){
Animal x = new Dog();
x.eat();
}
}
在这个例子中,Dog类继承了Animal类,并重写了Animal类中的eat()方法。当Animal x = new Dog()时,父类Animal的引用指向了子类Dog,即Dog对象也是Animal对象,所以会输出“Dog is barking and eating”的结果。
2.接口
另一种实现Java多态的方式是通过接口。与继承相比,接口有更高的抽象级别,因为它只是一系列方法的集合而不是可实例化的类。当一个类实现了一个接口时,该类必须实现该接口中声明的所有方法。
例如:
interface Animate{
void animate();
}
class Dog implements Animate{
public void animate(){
System.out.println("Dog is wagging his tail");
}
}
public class Test{
public static void main(String[] args){
Animate x = new Dog();
x.animate();
}
}
在这个例子中,Dog类实现了Animate接口,而Animate接口只有一个方法animate()。当Animate x = new Dog()时,接口Animate的引用指向了子类Dog,即Dog对象也是Animate对象,所以会输出“Dog is wagging his tail”的结果。
3.泛型
另一种实现Java多态的方式是通过泛型。泛型允许我们编写可以应用于多种类型的代码,从而提供了一种更通用的解决方案。可以建立一个泛型方法,在不同的时候传入不同类型的参数。这种方法常常用于集合类中。
例如:
class GenericClass{
public <T> void print(T t){
System.out.println(t.getClass().getName() + " = " + t);
}
}
public class Test{
public static void main(String[] args){
GenericClass gc = new GenericClass();
gc.print(123);
gc.print("Hello World");
}
}
在这个例子中,GenericClass类有一个泛型方法print(),可以打印任何类型的参数。当调用gc.print(123)时,会输出“java.lang.Integer = 123”的结果,而调用gc.print("Hello World")时,会输出“java.lang.String = Hello World”的结果。
本文来自投稿,不代表亲测学习网立场,如若转载,请注明出处:https://www.qince.net/javaho0ejava.html
郑重声明:
本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。 若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。
我们不承担任何技术及版权问题,且不对任何资源负法律责任。
如遇到资源无法下载,请点击这里失效报错。失效报错提交后记得查看你的留言信息,24小时之内反馈信息。
如有侵犯您的版权,请给我们私信,我们会尽快处理,并诚恳的向你道歉!