• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

this and super

 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What the below means?

A constructor in a subclass can access the class's inherited members directly. The keyword super can also be used in a subclass constructor to access inherited members via its super class. One might be tempted to use the super keyword in the constructor to specify initial values of inherited fields. However the super () construct provides a better solution, using superclass constructor to initialize inherited state
 
Marshal
Posts: 79716
381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a subtle mistake in that; a constructor can't access superclass members if they are marked private.

The way I think of it is that every object has a part which "belongs to" itself and a part "which is" its superclass. [I am sure it's not accurate however.] You have to set up the "superclass" part first, so you call the superclass constructor with super(123, 456, "Campbell");

You can also write this() to call overloaded constructors in the same class.

The this() and super() calls must be the first statement in the constructor, so you can't call this() and super() in the same constructor. Every path through the constructors must call super() eventually. If you write super.name = "Campbell"; you ought to get a compiler error because the name field in the superclass ought to have been declared private.

If you don't write super() the compiler will assume you mean it and insert a super() call anyway.
 
Campbell Ritchie
Marshal
Posts: 79716
381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
By the way: Where was that quote from. It is always useful to Quote Sources.
 
You didn't tell me he was so big. Unlike this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic