OCA Java SE 8 Class Design - Java super








Calling Inherited Class Members

Java classes may use public or protected member from the parent class, including methods, primitives, or object references.

If the parent class and child class are from the same package, the child class can use any default members defined in the parent class.

Finally, a child class cannot access a private member from the parent class directly.

We can access private members from parent via a public or protected method.

To reference a member in a parent class, call it directly.

class Shape { 
  protected int size; 
  private int edge; 
   
  public Shape(int edge) { 
    this.edge = edge; 
  } 
   
  public int getEdge() { 
    return edge; 
  } 
} 

class Rectangle extends Shape { 

  private int numberOfFins = 8; 
         
  public Rectangle(int edge) { 
    super(edge); 
    this.size = 4;  
  } 
         
  public void displayRectangleDetails() { 
    System.out.print("Rectangle with edge: "+getEdge()); 
    System.out.print(" and "+size+" meters long"); 
    System.out.print(" with "+numberOfFins+" fins"); 
  } 
} 

You can use this to access members of the parent class that are accessible from the child class.

public void displayRectangleDetails() { 
  System.out.print("Rectangle with edge: "+this.getEdge()); 
  System.out.print(" and "+this.size+" meters long"); 
  System.out.print(" with "+this.numberOfFins+" fins"); 
} 

In Java, you can explicitly reference a member of the parent class by using the super keyword.

public void displayRectangleDetails() { 
  System.out.print("Rectangle with edge: "+super.getEdge()); 
  System.out.print(" and "+super.size+" meters long"); 
  System.out.print(" with "+this.numberOfFins+" fins"); 
} 

This code will not compile because numberOfFins is only a member of the current class, not the parent class.

public void displayRectangleDetails() { 
  System.out.print("Rectangle with edge: "+super.getEdge()); 
  System.out.print(" and "+super.size+" meters long"); 
  System.out.print(" with "+super.numberOfFins+" fins"); // DOES NOT COMPILE 
} 

If the child class overrides a member of the parent class, this and super could have very different effects when applied to a class member.





super() vs. super

this() and this are unrelated in Java.

super() and super are quite different.

super() is a statement that calls a parent constructor and can only be used in the first statement of a constructor from a child class.

super is a keyword to reference a member defined in a parent class and may be used from the child class.