Java继承怎么课前引入_【Java 基础篇】【第九课】继承

继承就是为了提高代码的复用率。

利用继承,我们可以避免代码的重复。让Woman类继承自Human类,Woman类就自动拥有了Human类中所有public成员的功能。我们用extends关键字表示继承:

看代码吧:

class Human

{

/*因为类中显式的声明了一个带参数构造器,所以默认的构造器就不存在了,但是你在子类的构造器中并没有显式

* 的调用父类的构造器(创建子类对象的时候,一定会去调用父类的构造器,这个不用问为什么),没有显式调用

* 的话,虚拟机就会默认调用父类的默认构造器,但是此时你的父类的默认构造器已经不存在了,这也就是为什么父

* 类中必须保留默认构造器的原因。

* PS.应该养成良好的编程习惯,任何我们自己定义的类,都显式的加上默认的构造器,以后更深入的学习之后,

* 会发现有很多好处

*/

public Human()

{

}

public Human(int h)

{

System.out.println("human construction");

this.height = h;

}

public int getHeight()

{

return this.height;

}

public void growHeight(int h)

{

this.height = this.height + h;

}

public void breath()

{

System.out.println("hu.....hu.....");

}

private int height;

}

class Woman extends Human

{

public Human giveBirth()

{

System.out.println("Give birth");

return (new Human(20));

}

}

public class test

{

public static void main(String[] args)

{

Woman girl = new Woman();

girl.breath();

girl.growHeight(100);

System.out.println(girl.getHeight());

Human baby = girl.giveBirth();

System.out.println(baby.getHeight());

baby.growHeight(12);

System.out.println(baby.getHeight());

}

}

输出:

hu.....hu.....100Give birthhuman construction2032

需要注意 的地方:

1.子类中要是要调用基类的成员变量的话,成员变量必须是 protected 或者是 public;

2.子类中可以使用super关键字来指代基类对象,使用super() 相当于调用基类的构造函数,super.成员也可以访问。

看代码吧:

class Human

{

public Human(int h)

{

System.out.println("human construction");

this.height = h;

}

public int getHeight()

{

return this.height;

}

public void growHeight(int h)

{

this.height = this.height + h;

}

public void breath()

{

System.out.println("hu.....hu.....");

}

protected int height;

}

class Woman extends Human

{

public Woman(int h)

{

super(h);

System.out.println("Woman construction");

}

public Human giveBirth()

{

System.out.println("Give birth");

return (new Human(20));

}

}

public class test

{

public static void main(String[] args)

{

Woman girl = new Woman(20);

girl.breath();

girl.growHeight(100);

System.out.println(girl.getHeight());

Human baby = girl.giveBirth();

System.out.println(baby.getHeight());

baby.growHeight(12);

System.out.println(baby.getHeight());

}

}

输出结果:human constructionWoman constructionhu.....hu.....120Give birthhuman construction2032

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值