在java中什么是多态,什么是java中的多态方法?

I'm studying java language for SCJP test.

It is little bit hard to understand "polymorphic method".

Could you explain it for me?

or give me some links?

解决方案

"Polymorphic" means "many shapes." In Java, you can have a superclass with subclasses that do different things, using the same name. The traditional example is superclass Shape, with subclasses Circle, Square, and Rectangle, and method area().

So, for example

// note code is abbreviated, this is just for explanation

class Shape {

public int area(); // no implementation, this is abstract

}

class Circle {

private int radius;

public Circle(int r){ radius = r ; }

public int area(){ return Math.PI*radius*radius ; }

}

class Square {

private int wid;

Public Square(int w){ wid=w; }

public int area() { return wid*wid; }

}

Now consider an example

Shape s[] = new Shape[2];

s[0] = new Circle(10);

s[1] = new Square(10);

System.out.println("Area of s[0] "+s[0].area());

System.out.println("Area of s[1] "+s[1].area());

s[0].area() calls Circle.area(), s[1].area() calls Square.area() -- and thus we say that Shape and its subclasses exploit polymorphic calls to the method area.

多态性是指在面向对象编程,一个对象可以以多种不同的方式呈现。在Java,最常见的多态发生在使用父类的引用来引用子类的对象。这意味着可以使用父类类型的引用来调用子类类型的方法。通过多态性,可以增强代码的灵活性和可扩展性。 在Java实现多态有两个关键点:继承和方法重写。首先,需要创建一个父类并定义一个抽象方法,这样可以确保子类需要实现该方法。然后,创建子类并重写父类的抽象方法,实现子类自己的逻辑。 举个例子,假设有一个抽象类Animal,其有一个抽象方法eat()。然后创建两个子类Dog和Cat,它们分别重写了eat()方法。在使用时,可以使用Animal类型的引用来引用Dog或Cat的对象,然后调用eat()方法。这样就实现了多态性。 代码示例的Test类展示了如何实现多态。首先,创建了一个Animal类型的引用an1,指向Dog的对象。然后调用了an1的eat()方法,它会调用Dog类重写的eat()方法。同样的,创建了一个Animal类型的引用an2,指向Cat的对象,然后调用了an2的eat()方法,它会调用Cat类重写的eat()方法。 总结来说,多态性是通过继承和方法重写实现的,它可以提高代码的灵活性和可扩展性。在Java多态性最常见的表现是使用父类的引用来引用子类的对象。这样可以根据实际情况调用子类的方法,实现不同的行为。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [java多态概念、实现原理详解](https://download.csdn.net/download/weixin_38672840/12782475)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Java多态的概念及简单实现](https://blog.csdn.net/weixin_47861286/article/details/125925026)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值