温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java基础之extends用法详解及简单实例

发布时间:2020-10-15 23:47:04 来源:脚本之家 阅读:135 作者:lqh 栏目:编程语言

 Java extends用法详解

概要:

 理解继承是理解面向对象程序设计的关键。在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。

(1)继承

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{ 
} 
 
public class TestNew { 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Animal an = new Animal(); 
    Fish fn = new Fish(); 
     
    an.breathe(); 
    fn.breathe(); 
  } 
} 

在eclipse执行得:

Animal breathe! 
Animal breathe! 

java文件中的每个类都会在文件夹bin下生成一个对应的.class文件。执行结果说明派生类继承了父类的所有方法。

(2)覆盖

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) { 
    // TODO Auto-generated method stub 
    Animal an = new Animal(); 
    Fish fn = new Fish(); 
     
    an.breathe(); 
    fn.breathe(); 
  } 
} 

执行结果:

Animal breathe
Fish breathe

在子类中定义一个与父类同名,返回类型,参数类型均相同的一个方法,称为方法的覆盖。方法的覆盖发生在子类与父类之间。另外,可用super提供对父类的访问。

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI