JAVA的extends使用方法

JAVA的extends使用方法

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

      理解继承是理解面向对象程序设计的关键。在Java中,通过keywordextends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在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提供对父类的訪问。

 

參考原文:http://tieba.baidu.com/f?kz=295170500

參考原文:http://zhidao.baidu.com/question/25517733.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/118181.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号