Java super keyword tutorial
-
super can use to call immediate parent class constructor.
public class Shape { private String name; private String color; public Shape(String name, String color) { this.name = name; this.color = color; } } public class Square extends Shape { private int lengthOfSide; public Square(String name, String color, int lengthOfSide) { super(name, color); this.lengthOfSide = lengthOfSide; } }
-
super can use to call immediate parent class methods.
public class Shape { private String name; private String color; public Shape(String name, String color) { this.name = name; this.color = color; } protected void printShape() { System.out.println("Printing a " + name); System.out.println("Color of the " + name + " is " + color); } } public class Square extends Shape { private int lengthOfSide; public Square(String name, String color, int lengthOfSide) { super(name, color); this.lengthOfSide = lengthOfSide; } public void printSquare() { super.printShape(); System.out.println("Length of a side is " + lengthOfSide); } }
-
super can use to call immediate parent class instant variables.
public class Shape { protected String name; protected String color; public Shape(String name, String color) { this.name = name; this.color = color; } } public class Square extends Shape { private int lengthOfSide; public Square(String name, String color, int lengthOfSide) { super(name, color); this.lengthOfSide = lengthOfSide; } public void printSquare() { System.out.println("Printing a " + super.name); System.out.println("Color of the " + super.name + " is " + super.color); System.out.println("Length of a side is " + lengthOfSide); } }
<< Java this keyword Java static keyword >>