super java使用方法_java关键字之super使用方法

super关键字有两个作用:

1、调用超类方法

2、调用超类的构造器

Accessing Superclass Members

If your method overrides one of its superclass’s methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

publicclassSuperclass{publicvoidprintMethod(){System.out.println("Printed in Superclass.");}}

Here is a subclass, called Subclass, that overrides printMethod():

publicclassSubclassextendsSuperclass{publicvoidprintMethod(){//overrides printMethod in Superclasssuper.printMethod();System.out.println("Printed in Subclass");}publicstaticvoidmain(String[]args){Subclasss=newSubclass();s.printMethod();}}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.

Printed in Subclass

Subclass Constructors

The following example illustrates how to use the super keyword to invoke a superclass’s constructor. Recall from the Bicycle example that MountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:

publicMountainBike(intstartHeight,intstartCadence,intstartSpeed,intstartGear){super(startCadence,startSpeed,startGear);seatHeight=startHeight;}

Invocation of a superclass constructor must be the first line in the subclass constructor.

The syntax for calling a superclass constructor is

super();

--or--

super(parameter list);

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

——————————————————————————–

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

——————————————————————————–

If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值