Super keyword (calling superclass methods)

With the Super keyword, you can:

  • Call superclass methods
  • Call superclass constructors
  • Look at the following example:

    public class Test {
    	
    	public static void main(String[] args)
    	{
    		Square mysquare = new Square();
    		mysquare.getInformation();
    		
    	}
    }
    
    
    class Shape // the SUPERCLASS
    {
    	int color = 4;
    			
    	public void getInformation() // getInformation() in the superclass
    	{
    		System.out.println(color);
    	}
    }
    
    class Square extends Shape // the SUBCLASS
    {
    	String sides="4 sides";
    	
    	public void getInformation() // getInformation() in the subclass
    	{
    		getInformation();
    	}
    }
    

    This outputs:

    Exception in thread “main” java.lang.StackOverflowError
    at Square.getInformation(Test.java:30)
    at Square.getInformation(Test.java:30)
    at Square.getInformation(Test.java:30)

    Why the error?

    At line 28, the call to method getInformation() actually has “this” appending to it automatically:

    this.getInformation()

    “this” refers to the object that called it “mysquare”

    So what happens is a cycle that goes round and round and crashes the program.

    However, if we use the “super” keyword

    super.getInformation() as follows on line 28

    public class Test {
    	
    	public static void main(String[] args)
    	{
    		Square mysquare = new Square();
    		mysquare.getInformation();
    		
    	}
    }
    
    
    class Shape // the SUPERCLASS
    {
    	int color = 4;
    			
    	public void getInformation() // getInformation() in the superclass
    	{
    		System.out.println(color);
    	}
    }
    
    class Square extends Shape // the SUBCLASS
    {
    	String sides="4 sides";
    	
    	public void getInformation() // getInformation() in the subclass
    	{
    		super.getInformation();
    	}
    }
    

    This outputs:

    4

    The getInformation() method in the SUPERCLASS is being called (the Shape class)

    Leave a Reply