举例:
class Animal{
void eat(){
System.out.println("Animal eat")
}
void sleep(){
System.out.println("Animal sleep")
}
void breathe(){
System.out.println("Animal breathe")
}
}
class Fish extends Animal{
void breathe(){
System.out.println("Fish breathe")
}
}
public class TestNew {
public static void main(String[] args) {
Animal an = new Animal()
Fish fn = new Fish()
an.breathe()
fn.breathe()
}
}
执行结果:
Animal breathe
Fish breathe
在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。举例:
class
Animal{
void
eat(){
System.out.println("Animal
eat")
}
void
sleep(){
System.out.println("Animal
sleep")
}
void
breathe(){
System.out.println("Animal
breathe")
}
}
class
Fish
extends
Animal{
void
breathe(){
System.out.println("Fish
breathe")
}
}
public
class
TestNew
{
public
static
void
main(String[]
args)
{
Animal
an
=
new
Animal()
Fish
fn
=
new
Fish()
an.breathe()
fn.breathe()
}
}
执行结果:
Animal
breathe
Fish
breathe
从概念上来说,extends表示的是类与类或接口与接口的继承,implements表示的是类对接口的实现。也就是说,一个是扩展,另一个是实现。\x0d\x0a从设计思路来回答,就要讲明白为什么会有类和接口这两个不同的概念。\x0d\x0a事实上,仅仅通过类的单继承就可以解决绝大部分问题,而C++的多重继承可以解决任何面向对象问题。之所以要设计接口这个概念,主要还是为了使面向对象设计中的多态得到优美的解决。\x0d\x0a接口是一个特殊的抽象类。Java的设计者认为,多重继承增加了系统设计和实现时的复杂性,并且容易出错和产生歧义(例如A同时继承了B和C,而A定义了一个方法,在B和C中都存在这个方法的同名方法,此时A重写了B还是C的方法?),因此Java只允许单重继承,这完全是Java的设计者强加的限制。\x0d\x0a为了解决单重继承无法解决的问题(或者说不容易解决的问题),Java设计者设计了接口的概念,实际上,Java设计者鼓励使用接口而不是继承,因为接口的抽象性更加纯粹。\x0d\x0a\x0d\x0a总结:单继承+接口和多继承都是为了解决面向对象问题,只是方式不同。在Java设计者看来,单继承+接口的好处 >多继承