Java Keywords (Part XVI): The many uses of the super keyword

We are up to 40 keywords covered in previous articles! That's 83% keywords covered. We have only 8 keywords to cover and I will be covering 1 of those in this article. We are almost done with all the basic keywords. This article will illustrate the use of the keyword super. I suggest you start with Java Keywords (Part I) before proceeding further, if you have not read any of the previous articles in the Java Keyword series. Also, go back and read the one about Data Types. All of these articles are from September 2018. That should help you find them quickly. You can also use the "search" option at the top of this page. The series was written with natural progression in mind. Therefore, some of the keywords already covered may be used in code examples illustrated here.

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.

The super Keyword

Of the two keywords discussed in this article, super is the easiest to learn because it has a two functions. It is used to refer to variables and overridden methods in the superclass and it is used to call the superclass constructor. I will illustrate the latter first because it is the simplest.

Calling the super constructor


public class ParentClass {
	public ParentClass() {
        System.out.println("From ParentClass constructor");
    }
}

public class ChildClass extends ParentClass {
	public ChildClass() {
    	super();
        System.out.println("From ChildClass constructor");
    }
    
    public static void main(String[] args) {
    	new ChildClass();
    }
}
If the above code is executed, it will print out "From ParentClass constructor" first and then "From ChildClass constructor" last. That should not be a surprise. What you may not know is that the inclusion of super() is not neccessary. In the future, I will write a separate article on constructors to explain this topic in more detail. For now, just know that if you omit super(), the compiler will add it for you; even if you don't explicitly extend a class.

The second thing to know is that you can call super() with arguments so long there is a constructor in the parent class that has the same number and type of arguments.


public class Polygon {
	protected String color;
    
    public Polygon() {...}
    public Polygon(String color) {this.color = color;}
	...
}

public class Square exends Polygon {
	private int sideLength;
    
    public Square() {
    	// no need to call super()
        sideLength = 1;
    }
    
    public Square (int sideLength) {
    	super("white"); // This has to be called explicitly
        this.sideLength = sideLength;
    }
    ...
}
Calls to super() with arguments must be made explicitly. Other than zero arguments, the compiler cannot make any assumptions regarding what call to a super-class constructor needs to be made. Again, more on this topic in a future article. For now, we covered the basics on using super to call the parent class constructor.

Using super to reference variables and methods


public class Polygon {
	protected String color;
    
    public Polygon() {...}
    public Polygon(String color) {this.color = color;}
	...
}

public class Square exends Polygon {
	private int sideLength;
    private Color color;
    
    public Square() {
    	// no need to call super()
        sideLength = 1;
    }
    
    public Square (int sideLength) {
    	super.color = "white"; // This is a terrible example, bear with me...
        this.sideLength = sideLength;
    }
    ...
}
Using super to reference variables is not very common. In this example, we replaced the call to super(String) with direct access to the parent class color variable. This cannot be done for private variables in the parent class. However, it is not necessary to use super to reference a parent class variable unless the child class contains a variable with the same name as one found in the parent class. In this example, a
"color"
exists in both classes. Therefore, to distiguish between the two, you must use super to reference the parent class variable. Having accessible variables in the parent class with the same name as one found in the child class is known as "Hidding Fields" and it is highly discouraged. For that reason, using super to reference a parent class variable is not very common as I previously stated.

The second (and last) case in this section is to using super to reference a parent class method.


public class Polygon {
	protected String color;
	...
    public void printMyInfo() {
    	System.out.println("I am a " + color + " polygon.");
    }
}

public class Square exends Polygon {
    ...
    @Override
    public void printMyInfo() {
    	super.printMyInfo();
        System.out.println("I am specifically a square.");
    }
}
As in the case of variables, if you need to call a method in the super class that has not been overridden in the child class, using super is not necessary. Using super is only necessary to reference overridden methods.

One last thing to consider

In the previous article, you learned about using this to chain constructor calls and here you learned about using super to call constructors of the super class. It is prudent to mention here that the use of these keywords in this context is mutually exclusive. That means you cannot use both in the same constructor.

public class ChildClass extends ParentClass {
	public ChildClass() {
    	super();
        System.out.println("From ChildClass constructor");
    }
    
    public ChildClass(String s) {
    	this();
        super(s); // not allowed
        ...
    }
}
Even if you switch the order between this and super, the second one will result in a compiling error. With this, I conclude the articles related to the use of this and super. I hope they were helpful.

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

The Beauty of the Null Object Pattern

Exception Handling: File CRUD Operations Example