2

I think I'm missing something, or something isn't clicking for me. I'm reading a book on java, and I just learned about super(). When used to get a constructor, it gets the constructor from one superclass up, correct? What if you wanted to go two superclasses up, how would that be done?

Something's just not sitting right in my brain, and I'm hoping this question will help me put the pieces together.

Korey Hinton
  • 2,532
  • 2
  • 25
  • 24
Sharpevil
  • 194
  • 5
  • 18

2 Answers2

8

You can't go two levels up. You can only decide to call your parent. That class is then responsible for calling its parent in turn.

Note that all constructors (except for the root constructors in Object) call a super constructor. If you don't specify it explicitly, or, as @PaulBellora adds, the first statement is a this() call to another constructor of your class, the compiler inserts a super() call as the first statement in every constructor.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Keppil
  • 45,603
  • 8
  • 97
  • 119
1

It can only go to the one above it since a class can only inherit from 1 class, and its parent class can only inherit from 1 class and it will call its own parent's constructor.

class GrandParent
{
      GrandParent()
      {
      }
 }

class Parent extends GrandParent
{
     Parent() {
          super(); //calls GrandParent()
     }
}

class Child extends Parent
{
      Child() {
           super(); //calls Parent()
      }
}
Korey Hinton
  • 2,532
  • 2
  • 25
  • 24