java继承和多态的异同,继承和多态之间的区别

I was studying about polymorphism. I couldn't determine the analogy in Java about these two features.

Let's say Animal class is a concrete superclass with Cat and Dog as its subclasses. I know that this is a case of inheritance. But isn't Cat and Dog classes, polymorphs of Animal class?

I am well aware of interfaces in Java. I couldn't understand why interfaces are used instead of concrete classes to explain polymorphism. It could be that the whole purpose of creating interface is to create polymorphs but I want to know why interfaces and not concrete classes?

解决方案

class Animal{

public void speak(){ System.out.println("Speaking something");}

}

class Person extends Animal{

@Override

public void speak(){ System.out.println("Hello..");}

}

Animal a = new Person();

a.speak();// Hello

The dictionary definition of polymorphism refers to a principle in

biology in which an organism or species can have many different forms

or stages. This principle can also be applied to object-oriented

programming and languages like the Java language. Subclasses of a

class can define their own unique behaviors and yet share some of the

same functionality of the parent class [..]

Why Interface ?

You know what needs to be done, but you want implementers to decide how to do it, You will let implementer implement the stuffs forcefully

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值