Mark As Completed Discussion

Accessing Super Class

To recap what you've seen before, classes can be derived from other classes. With this inheritance-derivation relationship, the whole system can be viewed as a class hierarchy. Inside the hierarchy, there are some definitions to keep in mind which are similar to the tree data structure.

Accessing Super Class

  1. Subclass: A class that is derived from another class is called a subclass.
  2. Superclass: The class from which a subclass is derived is called the superclass.
  3. Siblingclass: If two classes are derived from the same parent, then they are siblingclasses. Keep in mind that this is different from sibling nodes in a tree where all the nodes at the same level are sibling nodes. In the context of OOP, sibling classes must have the same parent.

Inheriting from a class means that you are extending the class's capabilities (or changing them). What if you don't want to totally replace the functionality of a method you are overriding? In that case, you need to somehow call the previous method first, then add other instructions. The initial method before inheritance can be accessed using the super keyword.

For example, when you create a constructor for the Square class, you only need 1 value (the side). Since it is derived from the Rectangle class, you should just reuse the Rectangle constructor. You can do it like so:

Accessing Super Class

TEXT/X-JAVA
1public class Square extends Shape {
2    public Square(int side) {
3        // This calls the super constructor
4        super(side, side);
5        // If you want, you can also do other things here
6    }
7
8    // This method is unnecessary
9    // But for demo we are showing it to you.
10    @Overriding
11    public double getArea() {
12        return super.getArea();
13    }
14}