前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【java基础】Java extends用法详解

【java基础】Java extends用法详解

作者头像
程序员互动联盟
发布2018-03-16 17:04:15
2K0
发布2018-03-16 17:04:15
举报
文章被收录于专栏:程序员互动联盟

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

(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();

}

}

执行结果

Animal breathe!

Animal breathe!

(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提供对父类的访问。

修改自:http://www.jb51.net/article/106795.htm

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-02-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员互动联盟 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档