0% found this document useful (0 votes)
7 views13 pages

Understanding Java Super Constructors

The super keyword in Java allows subclasses to access superclass members, including overridden methods, attributes with the same name, and constructors. It is essential for calling superclass methods and constructors explicitly, especially when dealing with parameterized constructors. The document provides examples illustrating the use of super in various scenarios, demonstrating its importance in Java inheritance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

Understanding Java Super Constructors

The super keyword in Java allows subclasses to access superclass members, including overridden methods, attributes with the same name, and constructors. It is essential for calling superclass methods and constructors explicitly, especially when dealing with parameterized constructors. The document provides examples illustrating the use of super in various scenarios, demonstrating its importance in Java inheritance.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java super

The super keyword in Java is used in subclasses to access superclass


members (attributes, constructors and methods).
Before we learn about the super keyword, make sure to know
about Java inheritance.

Uses of super keyword


1. To call methods of the superclass that is overridden in the
subclass.
2. To access attributes (fields) of the superclass if both
superclass and subclass have attributes with the same name.
3. To explicitly call superclass no-arg (default) or parameterized
constructor from the subclass constructor.
Let's understand each of these uses.
1. Access Overridden Methods of the superclass
If methods with the same name are defined in both superclass and
subclass, the method in the subclass overrides the method in the
superclass. This is called method overriding.
Example 1: Method overriding
classAnimal{
// overridden methodpublicvoiddisplay(){
[Link]("I am an animal");
}
}
classDogextendsAnimal{
// overriding method@Overridepublicvoiddisplay(){
[Link]("I am a dog");
}
publicvoidprintMessage(){
display();
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = newDog();
[Link]();
}
}
Output
I am a dog
In this example, by making an object dog1 of Dog class, we can call its
method printMessage() which then executes the display() statement.
Since display() is defined in both the classes, the method of
subclass Dog overrides the method of superclass Animal. Hence,
the display() of the subclass is called.
What if the overridden method of the superclass has to be called?
We use [Link]() if the overridden method display() of
superclass Animal needs to be called.
Example 2: super to Call Superclass Method
classAnimal{
// overridden methodpublicvoiddisplay(){
[Link]("I am an animal");
}
}
classDogextendsAnimal{
// overriding method@Overridepublicvoiddisplay(){
[Link]("I am a dog");
}
publicvoidprintMessage(){
// this calls overriding methoddisplay();
// this calls overridden [Link]();
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = newDog();
[Link]();
}
}
Output
I am a dog
I am an animal
Here, how the above program works.

2. Access Attributes of the Superclass


The superclass and subclass can have attributes with the same name.
We use the super keyword to access the attribute of the superclass.
Example 3: Access superclass attribute
classAnimal{
protectedString type="animal";
}
classDogextendsAnimal{
publicString type="mammal";
publicvoidprintType(){
[Link]("I am a "+ type);
[Link]("I am an "+ [Link]);
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = newDog();
[Link]();
}
}
Output:
I am a mammal
I am an animal
In this example, we have defined the same instance field type in both
the superclass Animal and the subclass Dog.
We then created an object dog1 of the Dog class. Then,
the printType() method is called using this object.
Inside the printType() function,
• type refers to the attribute of the subclass Dog.
• [Link] refers to the attribute of the superclass Animal.
Hence, [Link]("I am a " + type); prints I am a mammal.
And, [Link]("I am an " + [Link]); prints I am an animal.
3. Use of super() to access superclass constructor
As we know, when an object of a class is created, its default constructor
is automatically called.
To explicitly call the superclass constructor from the subclass
constructor, we use super(). It's a special form of the super keyword.
super() can be used only inside the subclass constructor and must be
the first statement.
Example 4: Use of super()
Class Animal{
// default or no-arg constructor of class Animal
Animal() {
[Link]("I am an animal");
}
}
Class Dog extends Animal
{
// default or no-arg constructor of class Dog
Dog()
{
// calling default constructor of the super class
super();
[Link]("I am a dog");
}
}
Class Main{
public static void main(String[] args)
{
Dog dog1 = newDog();
}
}
Output
I am an animal
I am a dog

Here, when an object dog1 of Dog class is created, it automatically calls


the default or no-arg constructor of that class.
Inside the subclass constructor, the super() statement calls the
constructor of the superclass and executes the statements inside it.
Hence, we get the output I am an animal.

The flow of the program then returns back to the subclass constructor
and executes the remaining statements. Thus, I am a dog will be
printed.
However, using super() is not compulsory. Even if super() is not used in
the subclass constructor, the compiler implicitly calls the default
constructor of the superclass.
So, why use redundant code if the compiler automatically invokes
super()?
It is required if the parameterized constructor (a constructor that takes
arguments) of the superclass has to be called from the subclass
constructor.
The parameterized super() must always be the first statement in the
body of the constructor of the subclass, otherwise, we get a
compilation error.
Example 5: Call Parameterized Constructor Using super()
classAnimal
{
// default or no-arg constructorAnimal() {
[Link]("I am an animal");
}
// parameterized constructor Animal(String type) {
[Link]("Type: "+type);
}
}
Class Dog extends Animal{
// default constructorDog() {
// calling parameterized constructor of the superclasssuper("Animal");
[Link]("I am a dog");
}
}
classMain{
publicstaticvoidmain(String[] args){
Dog dog1 = newDog();
}
}
Output
Type: Animal
I am a dog
The compiler can automatically call the no-arg constructor. However, it
cannot call parameterized constructors.
If a parameterized constructor has to be called, we need to explicitly
define it in the subclass constructor.

Note that in the above example, we explicitly called the parameterized


constructor super("Animal"). The compiler does not call the default
constructor of the superclass in this case.

Super Demo
Class A
public class ClassA
{
int x ;
ClassA()
{
//x = 10;
[Link]("Constructor of ClassA");
}
ClassA(int x )
{
this.x = x;
[Link]("Constructor of ClassA");
}

void disp()
{
[Link]("Display of ClassA : x = "+x);
}
}
=======================
public class ClassB extends ClassA
{
int x ;
ClassB()
{
super(10);
[Link]("Constructor of ClassB");
//x = 100;
}
ClassB(int x)
{
super(10);
this.x = x;
[Link]("Constructor of ClassB");
//x = 100;
}
void disp()
{
[Link]();
[Link]("Display of ClassB : x = "+x+ " x = "+super.x);
}
}
============
public class ClassC extends ClassB
{
int x ;
ClassC()
{
//x = 1000;
super(100);
[Link]("Constructor of ClassC");
}
ClassC(int x )
{
super(100);
this.x = x;
[Link]("Constructor of ClassC");
}
void disp()
{
[Link]();
[Link]("Display of ClassC : x = "+x+ " x = "+super.x);
}
}
========================
public class Main {
void main()
{
ClassC c1 = new ClassC(1000);
[Link]();
}
}
---------------
Output
Constructor of ClassA
Constructor of ClassB
Constructor of ClassC
Display of ClassA : x = 10
Display of ClassB : x = 100 x = 10
Display of ClassC : x = 1000 x = 100

Process finished with exit code 0

Common questions

Powered by AI

Constructor overloading in Java allows a class to have more than one constructor with different parameter lists. In an inheritance context, 'super' facilitates invoking these overloaded constructors in the superclass. When a subclass needs to provide initial values to the superclass, a specific overloaded constructor can be called using 'super()'. This is important for flexible object creation, allowing subclasses to initialize superclass attributes with specific values. This interaction is highlighted in the example where 'ClassB' and 'ClassC' choose which overloaded constructor of 'ClassA' to invoke based on the context, using 'super(10)' to call the constructor with an integer parameter .

Inheritance in Java provides a mechanism for a subclass to inherit attributes and methods from a superclass, promoting code reuse and supporting the concept of "is-a" relationships. It manages state by allowing subclasses to have both inherited state from superclasses and their unique attributes. Behavior is managed through method inheritance and overriding. The 'super' keyword plays a crucial role by enabling subclasses to access and utilize the state and behavior defined in the superclass, even when overridden. It ensures that the intended behaviors of superclass methods and the states represented by its attributes are not lost or obscured, thereby maintaining architectural clarity and enabling effective state and behavior management .

Using 'super()' in a subclass constructor directly influences the initialization process and execution order in Java. 'super()' must be the first statement in a subclass constructor and ensures that the superclass is initialized before the subclass's constructor logic is executed. When 'super()' is called, it triggers the execution of the specified constructor in the superclass, completing all its initializations before returning control to the subclass. This establishes a clear top-down execution order, where each level of the class hierarchy is initialized in sequence. This order guarantees that all inherited aspects are properly set up before subclass-specific initialization occurs, ensuring a consistent object state across the hierarchy .

When a superclass and its subclass have attributes with the same name, the 'super' keyword is used to specify that the superclass's version of the attribute is being referred to. For example, if the superclass 'Animal' has a protected attribute 'type' set to 'animal', and the subclass 'Dog' has the same attribute name set to 'mammal', using 'super.type' in 'Dog' will access the 'type' in 'Animal'. Without 'super', accessing 'type' within 'Dog' refers to its own attribute. This avoids name hiding and allows both versions to be utilized in methods within the subclass .

The 'super' keyword in Java is used for three main purposes: accessing overridden superclass methods, accessing superclass attributes, and explicitly calling superclass constructors. In method overriding, 'super' allows calling the overridden method of the superclass from the subclass. For attributes, if both superclass and subclass have fields with the same name, 'super' distinguishes the superclass attribute, avoiding ambiguity. The 'super()' keyword, used within subclass constructors, explicitly calls the constructor of the immediate superclass. This is particularly beneficial when the superclass only has parameterized constructors, which the compiler does not automatically call without an explicit 'super()' statement .

The 'super' keyword in Java facilitates polymorphism by enabling subclasses to explicitly call methods from their superclass, even when these methods have been overridden. In polymorphism, a reference of a superclass type can hold objects of its subclass, allowing the overridden method in the subclass to be called by default. Using 'super', one can bypass this and call the specific method implementation in the superclass directly, thus providing more versatile and controlled polymorphic behavior. This feature is essential when the original method's functionality in the superclass still needs to be accessible or necessary alongside the overridden method's behavior in the subclass .

Constructor chaining in Java involves sequentially calling multiple constructors across different levels of an inheritance hierarchy. When an object is instantiated, the constructors of all its superclasses are invoked in order from the topmost superclass down to the actual class being instantiated. For instance, in an inheritance chain involving classes 'ClassA', 'ClassB', and 'ClassC', where 'ClassC' extends 'ClassB' and 'ClassB' extends 'ClassA', creating an object of 'ClassC' involves first calling the constructor of 'ClassA', then 'ClassB', and finally 'ClassC'. This sequence can involve parameter passing as demonstrated when 'ClassC' uses 'super(100)' to call the parameterized constructor of 'ClassB', which in turn uses 'super(10)' to invoke 'ClassA’s' constructor. Such structured initialization ensures all superclass objects are properly initialized before the subclass .

Explicit use of 'super()' is necessary when a superclass has parameterized constructors that need to be called from the subclass constructor. By default, Java will only automatically invoke the no-argument constructor of the superclass unless specified otherwise. If the superclass lacks a default constructor or if specific constructor parameters must be passed, 'super()' must be explicitly used to ensure these constructors are called properly, as automatic invocation does not occur for parameterized constructors. This design consideration enables precise constructor chaining and helps maintain correct object initialization .

In Java, method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The 'super' keyword is used to call the overridden method from the superclass within the subclass, allowing the subclass to use the original version. For example, in a class hierarchy where class 'Dog' extends class 'Animal', both having a method 'display()', calling 'super.display()' within the 'Dog' class will execute the 'Animal' class's version of 'display()' instead of the overridden version in 'Dog' .

In Java, if a superclass does not have a no-argument constructor and one is not explicitly called from a subclass, a compilation error will occur. This is because the Java compiler attempts to automatically call the no-argument constructor of the superclass. If it doesn't exist, the subclass must use 'super()' to explicitly invoke a different constructor, such as a parameterized one. This ensures all necessary constructors are executed, thus initializing the object correctly. Failure to do so compromises object integrity by skipping essential initialization steps defined in the superclass .

You might also like