public class Point3D extends Point { public int z;
public Point3D(int x, int y, int z) { super(x,y); this.z = z; } }
this is the start of a program I'm working on that adds a third variable to the Point class. I'm not quite sure why it is neccesary to use the super() method. Aren't you making a constructer method without it? And what about the "this" part?
posted
I think I've got it: the super() method sets the x,y variables to what is defined in the superclass; the this thing refers to the object being made.
Posts: 3060 | Registered: Nov 2003
| IP: Logged |
posted
It is not strictly necessary to have 'super' in all cases. If Point had a default constructor, say setting both x and y to zero, then you could do without it. But since it doesn't (if I remember rightly) the poor compiler needs to know how it should initialise the members of the superclass.
Now, this may appear rather obvious to you; in fact, for this example, you don't really care what the compiler does about the superclass, you can set its members yourself. But that's because the Point class is deceptively simple and has public members, and compilers aren't very bright anyway. In a more complex case, your derived class might not have access to the members of the superclass, members which absolutely need to be set. Hence the call to super.
About 'this', that's your own fault for making the code difficult. You have a local variable, the 'z' passed to the constructor, masking (that is, it has the same name as) a member variable, the 'z' belonging to the Point class. This is a bad idea! In fact, if you look back a couple of pages, you'll find a thread of mine titled 'Good news, bad news' where I give an example of the possible consequences of that mistake. In my case it was very un-pretty.
But getting back to 'this' : The keyword dis-ambiguates the 'z' for the compiler. "this.z" means "the z variable belonging to the particular object that I am now working with", that is, the one you are constructing. Just plain 'z', on the other hand, means "whatever variable you can find called z", and this will find the local variable first. Now, if you had
code:
public Point3D(int x, int y, int setZToThis) { super(x,y); z = setZToThis; }
you wouldn't need the keyword, since 'z' is now un-ambiguous again - it can only refer to the member variable.
By the way, here's why masking variables is a bad idea; suppose you had said
z = someComplicatedCalculation();
Then the compiler would assign the result of someComplicatedCalculation() to the local z, which disappears as soon as the method is done! You would then be extremely confused when you later tried to use the member variable z, and found it hadn't been initialised.
Posts: 10645 | Registered: Jul 2004
| IP: Logged |