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.

3
  • 1
    stackoverflow.com/questions/11935895/… Take a look at this artice. Commented May 29, 2013 at 21:14
  • "Super() keyword… Can it be used to call a constructor more than one superclass up?" Yes. In fact, it's impossible not to. Just not directly. Commented May 29, 2013 at 21:18
  • 2
    What's the downvote for? I'm not getting it at all Commented May 29, 2013 at 21:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"the compiler inserts a super() call" - unless this() is called instead.
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() } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.