- Java super method example
- Java super method example
- 2) super can be used to invoke parent class method
- 3) super is used to invoke parent class constructor.
- Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
- super example: real use
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Using the Keyword super
- Subclass Constructors
- Overriding and Hiding Methods
- Static Methods
- Interface Methods
- Modifiers
- Summary
Java super method example
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Java super method example
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local.
To call the parent class method, we need to use super keyword.
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let’s see a simple example:
animal is created dog is created
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
animal is created dog is created
super example: real use
Let’s see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Using the Keyword super
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 :
Here is a subclass, called Subclass , that overrides printMethod() :
public class Subclass extends Superclass < // overrides printMethod in Superclass public void printMethod() < super.printMethod(); System.out.println("Printed in Subclass"); >public static void main(String[] args) < Subclass s = new Subclass(); 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:
public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear)
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
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.
Overriding and Hiding Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass’s method.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is «close enough» and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. For more information on @Override , see Annotations .
Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
- The version of the overridden instance method that gets invoked is the one in the subclass.
- The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Consider an example that contains two classes. The first is Animal , which contains one instance method and one static method:
public class Animal < public static void testClassMethod() < System.out.println("The static method in Animal"); >public void testInstanceMethod() < System.out.println("The instance method in Animal"); >>
The second class, a subclass of Animal , is called Cat :
public class Cat extends Animal < public static void testClassMethod() < System.out.println("The static method in Cat"); >public void testInstanceMethod() < System.out.println("The instance method in Cat"); >public static void main(String[] args) < Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); >>
The Cat class overrides the instance method in Animal and hides the static method in Animal . The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.
The output from this program is as follows:
The static method in Animal The instance method in Cat
As promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.
Interface Methods
Default methods and abstract methods in interfaces are inherited like instance methods. However, when the supertypes of a class or interface provide multiple default methods with the same signature, the Java compiler follows inheritance rules to resolve the name conflict. These rules are driven by the following two principles:
- Instance methods are preferred over interface default methods. Consider the following classes and interfaces:
public interface Mythical < default public String identifyMyself() < return "I am a mythical creature."; >>
public class Pegasus extends Horse implements Flyer, Mythical < public static void main(String. args) < Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); >>
public interface EggLayer extends Animal < default public String identifyMyself() < return "I am able to lay eggs."; >>
public interface FireBreather extends Animal
public class Dragon implements EggLayer, FireBreather < public static void main (String. args) < Dragon myApp = new Dragon(); System.out.println(myApp.identifyMyself()); >>
If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.
Consider the example about computer-controlled cars that can now fly. You have two interfaces ( OperateCar and FlyCar ) that provide default implementations for the same method, ( startEngine ):
public interface OperateCar < // . default public int startEngine(EncryptedKey key) < // Implementation >>
A class that implements both OperateCar and FlyCar must override the method startEngine . You could invoke any of the of the default implementations with the super keyword.
public class FlyingCar implements OperateCar, FlyCar < // . public int startEngine(EncryptedKey key) < FlyCar.super.startEngine(key); OperateCar.super.startEngine(key); >>
The name preceding super (in this example, FlyCar or OperateCar ) must refer to a direct superinterface that defines or inherits a default for the invoked method. This form of method invocation is not restricted to differentiating between multiple implemented interfaces that contain default methods with the same signature. You can use the super keyword to invoke a default method in both classes and interfaces.
Inherited instance methods from classes can override abstract interface methods. Consider the following interfaces and classes:
public class Mustang extends Horse implements Mammal < public static void main(String. args) < Mustang myApp = new Mustang(); System.out.println(myApp.identifyMyself()); >>
The method Mustang.identifyMyself returns the string I am a horse. The class Mustang inherits the method identifyMyself from the class Horse , which overrides the abstract method of the same name in the interface Mammal .
Note: Static methods in interfaces are never inherited.
Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.
Summary
The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Superclass Instance Method | Superclass Static Method | |
---|---|---|
Subclass Instance Method | Overrides | Generates a compile-time error |
Subclass Static Method | Generates a compile-time error | Hides |
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methodsthey are new methods, unique to the subclass.