详解Java中使用externds关键字继承类的用法
发布时间:2020-12-14 14:47:09 所属栏目:Java 来源:网络整理
导读:理解继承是理解面向对象程序设计的关键。在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。 (1)继承 class Animal{ void eat(){ System.out.println("Animal eat"); } void
理解继承是理解面向对象程序设计的关键。在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{ } 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提供对父类的访问。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java-mybaits-016-mybatis知识点StatementType
- java – 如何将图像绘制到JPanel或JFrame?
- mysql中数据库database、实例instance、会话session的关系
- java中字符串参数化符号${}的解析
- Java的比较接口comparable与comparator
- static、this、包--求n的阶乘
- 如何在Message Driven Beans中确认消息
- java – 无论应用程序如何启动,都可以找到conf文
- 你可以帮我收集Java Best Practices在线材料集合吗?
- 蓝牙连接失败“java.io.IOException:读取失败,套接字可能关