27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

General <strong>Java</strong> Questions I<br />

methods, there seems to be no value to considering one a member of the set of the<br />

other.<br />

Now, as far as teaching the language goes:<br />

Methods:<br />

+ return types<br />

+ called by name<br />

+ executed multiple times<br />

Constructors:<br />

+ super(...) or this(...) as first instructor (often implicit)<br />

- everything else<br />

I very much do not like trying to lump the two concepts together, especially in<br />

introductory courses. Conceptually they are very, very different things.<br />

A constructor is a unique element (even if there are several). It has the name of the<br />

class, its declaration is different, and it doesn't have the same syntax as a method. It<br />

plays a unique role. You can call a method from a constructor, but you cannot call a<br />

constructor from a method.<br />

I say constructors are distinct from methods, and for students, blurring the distinction<br />

will lead to problems.<br />

-by<br />

Chuck McCorvey, Chris Wolfe, Paul Lutus<br />

Q: Simple question: why constructor doesn't work in following example?<br />

class Start {<br />

public void Start() {<br />

System.out.println("Konstruktor START");<br />

}<br />

}<br />

public class Test {<br />

public static void main(String[] args) {<br />

Start s = new Start();<br />

}<br />

}<br />

Answer: Because you have included the return-type 'void' in the method declaration,<br />

it becomes a normal method, that just happens to have the same name as the class -<br />

so it won't get used as a constructor. Remove the 'void' and it should work.<br />

--<br />

Vince Bowdren<br />

P.S. by John: If you do not specifically define any constructors, the compiler inserts<br />

an invisible zero parameter constructor "behind the scenes". Often this is of only<br />

theoretical importance, but the important qualification is that you only get a default<br />

zero parameter constructor if you do not create any of your own.<br />

Your program used this zero parameter constructor and you saw nothing...<br />

Q: Why we can not declare constructor as final ?<br />

Answer: The keyword final when dealing with methods means the method cannot be<br />

overridden.<br />

file:///F|/350_t/350_tips/general_java-I.htm (5 of 31) [2002-02-27 21:18:17]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!