Java基础之extends用法详解及简单实例
Javaextends用法详解
概要:
理解继承是理解面向对象程序设计的关键。在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。
(1)继承
classAnimal{
voideat(){
System.out.println("Animaleat");
}
voidsleep(){
System.out.println("Animalsleep");
}
voidbreathe(){
System.out.println("Animalbreathe");
}
}
classFishextendsAnimal{
}
publicclassTestNew{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
Animalan=newAnimal();
Fishfn=newFish();
an.breathe();
fn.breathe();
}
}
在eclipse执行得:
Animalbreathe! Animalbreathe!
java文件中的每个类都会在文件夹bin下生成一个对应的.class文件。执行结果说明派生类继承了父类的所有方法。
(2)覆盖
classAnimal{
voideat(){
System.out.println("Animaleat");
}
voidsleep(){
System.out.println("Animalsleep");
}
voidbreathe(){
System.out.println("Animalbreathe");
}
}
classFishextendsAnimal{
voidbreathe(){
System.out.println("Fishbreathe");
}
}
publicclassTestNew{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
Animalan=newAnimal();
Fishfn=newFish();
an.breathe();
fn.breathe();
}
}
执行结果:
Animalbreathe Fishbreathe
在子类中定义一个与父类同名,返回类型,参数类型均相同的一个方法,称为方法的覆盖。方法的覆盖发生在子类与父类之间。另外,可用super提供对父类的访问。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短