Java – super & final

Home/Java - Tutorial/Java - Inheritance/Java – super & final
Java – super & final 2017-08-09T11:45:28+00:00

Java super & final :

Let us see now two most important keywords of java

1. super :

super keyword is used to call a superclass constructor and to call or access super class members(instance variables or methods).

syntax of super :

=> super(arg-list)

When a subclass calls super() it is calling the constructor of its immediate superclass.

super() must always be the first statement executed inside a subclass constructor.

=> super.member

Here member can be either method or an instance variables.

This second form of super is most applicable to situation in which member names of a subclass hide member of superclass due to same name.

EX :


Output :
i in superclass = 10
i in subclass = 12
The instance variable i in B1 hides the i in A, super allows access to the i defined in the superclass.
super can also be used to call methods that are hidden by a subclass.

2. final :

final keyword can be use with variables, methods and class.

=> final variables.

When we want to declare constant variable in java we use final keyword.

Syntax : final variable name = value;

=> final method

Syntax final methodname(arg)

When we put final keyword before method than it becomes final method.

To prevent overriding of method final keyword is used, means final method cant be override.

=> final class

A class that can not be sub classed is called a final class.

This is archived in java using the keyword final as  follow.

Syntax : final class class_name {   …   }

Any attempt to inherit this class will cause an error and compiler will not allow it.



Here no output will be there because all the comments in above  program are errors. Remove final keyword from class than you will get error like final method can not be override.

Prev Next