aspose file tools*
The moose likes Java in General and the fly likes Why super() or this() to be the first statement. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why super() or this() to be the first statement." Watch "Why super() or this() to be the first statement." New topic
Author

Why super() or this() to be the first statement.

Bandlamudi Narasimha Rao
Greenhorn

Joined: Nov 22, 2002
Posts: 2
I had a basic doubts, tried a lot to clarify from books, but i am not satisfied with the explanation given in any of the book. Could any of you give clear explanation with the proper example, i will be glad to you.
My doubts are,
1) When using the super() or this() in the constructor, it should be first the statement in the constructor., otherwise when compiling error will be throw, so in a constructor both willn't used at a time. Yes it is fine. Will same thing found in all the Java books. My doubt is why the super() or this() call to be first one, why they designed Java like this. Will it be a serious drawback in Java if it would have not been implemented (i.e., super() or this() should be the first statement in the constructor). Is this implementation is a great useful, otherthan initializing the class variables or similar use.
2) When a method is overridden in the the sub class, the overriding method should throw only the exceptions thrown by the overridden method or some of the exceptions thrown by the overridden method or sub classes of the exceptions thrown by the overridden method. Why is this restriction? If this restriction is not present how will it matter?.
3) When a method is overridden in the the sub class, the overriding methods accessibility should not be more restrictive than overridden method.


Narasimha rao B.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
hi Narasimha Rao ,
this is an interesting question. i've never questioned myself so far about these things. i am trying to think upon the issues you bought up. i have some thoughts about the issues 1 and 3rd you posed here. i am still working on issue 2 you mentioned.
issue 1:
--------
you might have noticed that if we have not initialized certain local variable to a method then compiler gives error that the variable might not have been initialized. why this is imposed? the reason is- Java was designed to make programmer's life easier. Java detects potential errors at compile time so that programmer doesn't run into "Run time errors" havocs like getting core dump, segmentation faults you know as far as possible...and bigger software can be implemented with less expectations of such stupid errors (have you ever faced a problem where just because of incorrect pointer access you had to spend 3-4 hours detecting it while coding in C??)
so, my point is "java design enforces initialization of each variable". now, this is important to understand why super() and this() needs to be called first.
there are two scenarios,
1. we explicitly invoke super() or this()
2. compiler implicitly invokes calls to super()
if we don't have any restriction then potentially what we can do?
we can write something like,

well, the above code will not compile but imagine what would happen if it gets compiled? we end up having "NullPointerException" when we run the code, right? if we are working on a huge project we don't expect this silly error to show up when we try to run the "demo code" in front of our managers, if you know what i mean.
so how does Java makes sure we don't have such errors which were obvious to occur just by looking at the code. (of course if we were having some runtime allocation from some method and it returns NULL then Java can't help us at compile time)? Java tries to find for such problems at compile time if it can and doesn't allow us to compile the code.
i would not disagree that my answers is terribly long but i'm poor at explaining certain tech stuff you know...
issue-3:
--------
this also can be argued in the same manner as above. imagine we have following code,

here say class A and B are some API classes. now if for some reason we are receiving object of type B (runtime type of the object) in reference of object ref of type A and looking at API for Class-A we see getMyfriendlist() to be public and calling that method then it won't work when we run the code, right? because in class B the method getMyfriendlist() is private.
so here the question is of flexible accessibility i guess. to make API classes design, which will be used by other users and third part developers, more helpful to the third party users.
i'm probably not clear here in descrbing my thoughts but i tried my best.
others please throw more light on this. we need to know "why" for certain things, don't we?
regards
maulin
James Chegwidden
Author
Ranch Hand

Joined: Oct 06, 2002
Posts: 201
Have you looked in the JLS for the answers to these questions?


Author and Instructor, my book
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
3)
Let's look at a simple piece of code:

If this was allowed, I would be able to do this:
A a = new B();
a.method1();
Polymorphism would then try to run method1 in B, but it is private so I would get a runtime error. Not good! By not allowing this situation, we avoid the problem.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
2) This creates similar problems to 3. Let's look at some code:

Now I can do this:

Because of polymorphism, a.method1() actually throws a SQLException which I don't catch. So the whole purpose of forcing me to catch exceptions is defeated. By not allowing this to occur we avoid the problem.
[ December 10, 2002: Message edited by: Thomas Paul ]
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
1) Constructors are actually run in the order of higest in the hierarachy first. So whenever I create a new object in Java, the constructor of the Object class is actually run first. However, Java does check to see if you want to run a different constructor than the default. It looks at the first line of the constructor to see if their is a reference to super() or this() before it goes up the hierarchy.
In C++ and C#, the same situation exists. There it is even more clear because you must specify the parent constructor in the constructor's signature and not in the constructor's code:
public MyClass(int i) : base(i) {}
sahin sarkar
Greenhorn

Joined: Dec 17, 2014
Posts: 4
I got most of what is being said here. But what I don't get is, what harm is there if we write this() or this(args) after the first statement.

writing super() as the first line is fine as child objects can't be created before parent class object. But what's with the this() issue. this() is also inside the same kind of constructor which is creating the object
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8419
    
  23

sahin sarkar wrote:I got most of what is being said here. But what I don't get is, what harm is there if we write this() or this(args) after the first statement.
writing super() as the first line is fine as child objects can't be created before parent class object. But what's with the this() issue. this() is also inside the same kind of constructor which is creating the object

And if any variables involved before such a call are only local, I completely agree.

So the answer is (as it is to most 'why' questions like this): I don't know.
Presumably the Founding Fathers had their reasons; but without a Vulcan mind-meld with one of them, we can only speculate.

My guess is: Because it was simplest.

Winston

PS: You do understand that you've revived a 12-year old thread? It's no big deal; but I suspect it's not far off a record.

PPS: Welcome to JavaRanch, sahin!

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
sahin sarkar
Greenhorn

Joined: Dec 17, 2014
Posts: 4
actually i started to learn java now and i didn't know about that record thing but i heard that this is a great place to put up doubts . and i also liked the approach of the people here.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8419
    
  23

sahin sarkar wrote:actually i started to learn java now and i didn't know about that record thing but i heard that this is a great place to put up doubts . and i also liked the approach of the people here.

Glad to hear it. And good luck with your studies.

About the only piece of advice I can give you is that "why" questions of this type are rarely productive, and are even less likely to produce the sort of definitive answer you want. Java, like any other language, has its "quirks"; and not all of them can be explained away by expertise.

If you want me to elaborate on my "guess": I suspect that the logic required for the compiler to allow local variables to be declared (and restricting those declarations) was more than they fancied taking on in version 1; so they replaced it with a simple rule: Constructor calls MUST be the first thing you do.

Since then, programmers have learned to live with it; so why change?

That's my guess. But it's only a guess.

Winston
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18987
    
    8

I learned object-oriented programming in a language which allowed you to call the superclass constructor anywhere in your constructor, and this was quite handy. So I found it annoying when Java didn't let me do that.

But lately it hasn't annoyed me as much. I must be getting used to it.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8419
    
  23

Paul Clapham wrote:...So I found it annoying when Java didn't let me do that.
But lately it hasn't annoyed me as much. I must be getting used to it.

Or maybe you've just joined the PSP (the Paranoid School of Programming).

If anyone is going to try and compromise a program, then a constructor is one of the best places to do it; so the more chances you give a programmer to make a mistake, that's where your vulnerability is going to be.

Java's simple rule prevents anything from happening before any constructor (this() or super()) is called, without it being explicitly expressed as a parameter; so even if someone does something stupid (or deliberate), it's there for all to see.

My 2¢.

Winston
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
… except possibly initialisers??
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why super() or this() to be the first statement.