java的super_Java中的Super()

一些事实:super()用于调用直系亲属。

super()可以与实例成员一起使用,即实例变量和实例方法。

super()可以在构造函数中调用父类的构造函数。

好了,现在让我们实际地实现以下几点super().

看看程序1和程序2之间的区别。在这里,程序2证明了我们对super()在爪哇。

程序1class Base{

int a = 100;}class Sup1 extends Base{

int a = 200;

void Show()

{

System.out.println(a);

System.out.println(a);

}

public static void main(String[] args)

{

new Sup1().Show();

}}

产出:200

200

现在查看程序2,并试图找出主要的区别。

程序2class Base{

int a = 100;}class Sup2 extends Base{

int a = 200;

void Show()

{

System.out.println(super.a);

System.out.println(a);

}

public static void main(String[] args)

{

new Sup2().Show();

}}

产出:100

200

在程序1中,输出只属于派生类。它无法打印基类和父类的变量。但是在程序2中,我们使用了super()带变数a同时打印其输出,而不是打印变量的值。a在派生类中,它打印变量的值。a基类的。所以这证明了super()用于调用直系亲属。

好的,现在看看程序3和程序4之间的区别。

程序3class Base{

int a = 100;

void Show()

{

System.out.println(a);

}}class Sup3 extends Base{

int a = 200;

void Show()

{

System.out.println(a);

}

public static void Main(String[] args)

{

new Sup3().Show();

}}

产出:200

这里的输出是200。当我们打电话Show(),Show()调用派生类的函数。但是如果我们想叫Show()父类的函数?请查看程序4以获得解决方案。

程序4class Base{

int a = 100;

void Show()

{

System.out.println(a);

}}class Sup4 extends Base{

int a = 200;

void Show()

{

super.Show();

System.out.println(a);

}

public static void Main(String[] args)

{

new Sup4().Show();

}}

产出:100

200

这里我们得到两个输出,100和200。当Show()函数调用派生类的函数,它首先调用Show()函数,因为在Show()函数的派生类,我们调用Show()函数,方法是将super关键字位于函数名称之前。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值