关闭

Java的extends使用方法

发表于:2015-2-12 09:59

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:mengfanrong    来源:51Testing软件测试网采编

  理解继承是理解面向对象程序设计的关键。在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提供对父类的訪问。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号