Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Data Persistence Using SQLite for Structured Data Setting Up the Database

Erin Kapoor
Erin Kapoor
412 Points

When to implement super()

I see a lot of methods have super(.....). When do we use super and we do we not want to use super? Thanks.

1 Answer

The concept is very much related to that of Inheritance

So basically super is used for two things a)call the superclass’ constructor and b) to access a member of the superclass which is hidden by a member of a subclass

Let me demonstrate both the uses in the same example

So let's assume we have a class A with a constructor, a String variable hello and a normal method called testThis().

class A {
    String hello;
    A() { 
        // some code 
    }

    public void testThis() {
      // some  code
  }

}

Now consider another class B which extends or inherits class A. The basic reason why we extend any class is so save effort in defining the basics all over again. So to avoid defining the meaning of B all over again we inherit the properties of A and add only those properties that B is concerned of since B is a special version of A.

So inside B's constructor we call its superclass's constructor (super should always be the first line inside the constructor)

Also if you notice the variable hello is repeated for both class A and class B. So which version of hello will be used when called? The version inside class B, since hello inside B will hide hello inside A.

class B extends A {
String hello;
     B() {
      super(); // this calls A's constructor
     // some code that only relates to specialised version of class A i.e. class B
    super.hello = "Inside A";  // this will refer to the hello defined in A
   hello = "Inside B"; // this will refer to hello inside B
    }
}

If the explanation looks confusing I would refer a quick read on inheritance.

Hope this helps