my dog learned polymorphism*
The moose likes Beginning Java and the fly likes this and super Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this and super" Watch "this and super" New topic
Author

this and super

Phillipe Rodrigues
Ranch Hand

Joined: Oct 30, 2007
Posts: 165
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


Thanks,
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
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
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
By the way: Where was that quote from. It is always useful to Quote Sources.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: this and super
 
Similar Threads
How does inheritance works?
What Inheritance Actually Do
super classes and sub classes
Inhertance
can we call super() outside constructor?