Java Forum / General / January 2008
Why does compiler only look at public methods of superclasses of...?
failure_to@yahoo.co.uk - 05 Jan 2008 21:06 GMT Hello
I haven't been learning Java for the past week or so, but now that I finally got back to it, I decided to refresh on few things I previously learned and thus the following questions about dynamic binding came to be:
Say we have class A reference variable called a. According to my book, when a.x() is called, the following steps take place ( I won't write all the steps taken ( or at least not in detail ), but just the ones that relate to my questions )
1) Compiler enumerates all methods in class A and all public methods in the superclasses of A to find methods named x
a) Why does compiler only look at public methods in superclasses of A?
b) besides, doesn't compiler also look at methods ( in superclasses of A ) which have default access specified ( it does on my system )? I find it strange that author of the book would forget to mention that
c) If compiler does look for both default and public methods in A's superclasses, then why doesn't it also look for methods with protected access modifier?
2) In the next step compiler determines the types of parameters supplied in the parameter call and finds exact or best match ( this process is called overloading resolution ) ...
3) if method is declared final, static or private then compiler knows what method to call else ...
Why point out that if method is private then compiler knows what method to call? I'm assuming that book is only talking about the case where private method x() is defined in class A and not in one of A's superclasses?! Else the above statement wouldn't make much sense since if method x() was declared only in one of A's superclasses ( with private access modifier ), then compiler would report an error and nothing else.
* This may be a silly question, but why can't you override a protected method? Surely there is some very good reason for java developers deciding not to allow this?!
thank you
Joshua Cranmer - 05 Jan 2008 22:05 GMT > Hello > [quoted text clipped - 7 lines] > all the steps taken ( or at least not in detail ), but just the ones > that relate to my questions ) The exact sequence is defined in JLS 3, §15.12. The full steps probably fills up a dozen or so pages, most of which are solely for generic and variable-argument methods. Since I am assuming generic and variadic method lookups are not in question here, I will excise that from my response.
> 1) Compiler enumerates all methods in class A and all public methods > in the superclasses of A to find methods named x The book is wrong. JLS 3 clearly states: The class or interface determined by compile-time step 1 (§15.12.1) is searched for all member methods that are potentially applicable to this method invocation; members inherited from superclasses and superinterfaces are included in this search.
The compiler would limit this methods to those that are potentially applicable: # The name of the member is identical to the name of the method in the method invocation. # The member is accessible (§6.6) to the class or interface in which the method invocation appears. # The arity of the member is lesser or equal to the arity of the method invocation. # If the member is a fixed arity method with arity n, the arity of the method invocation is equal to n. [ Variable-argument and generics points are removed from this list; the full list is at §15.12.2.1 ]
The correct statement should be: Compiler enumerates all accessible methods in class A and the superclasses and superinterfaces to find methods named x with the right number of arguments.
> 2) In the next step compiler determines the types of parameters > supplied in the parameter call and finds exact or best match ( this > process is called overloading resolution ) ... JLS 3 specifies several phases (but still one step). Roughly: Phase 1: Method is still probably applicable if the types of the formal parameters are subtypes are convertible from the expression type of the parameters. Phase 2: Same thing with a different type of convertibility Phase 3: Variable-argument resolution Phase 4: Pick the most specific method
> 3) if method is declared final, static or private then compiler knows > what method to call else ... I am assuming that this is supposed to be step 3 according to the JLS, which finds out all of the information: # The name of the method. # The qualifying type of the method invocation (§13.1). # The number of parameters and the types of the parameters, in order. # The result type, or void. # The invocation mode, computed as follows:
* If the compile-time declaration has the static modifier, then the invocation mode is static. * Otherwise, if the compile-time declaration has the private modifier, then the invocation mode is nonvirtual. * Otherwise, if the part of the method invocation before the left parenthesis is of the form super . Identifier or of the form ClassName.super.Identifier then the invocation mode is super. * Otherwise, if the compile-time declaration is in an interface, then the invocation mode is interface. * Otherwise, the invocation mode is virtual.
Most of the method resolution ("what method to call") comes from the runtime resolution process. The JVM spec governs this part of the process.
> Why point out that if method is private then compiler knows what > method to call? I'm assuming that book is only talking about the case > where private method x() is defined in class A and not in one of A's > superclasses?! It should be obvious why private methods are non-virtually called. I think the book is trying to summarize the JLS but is inaccurately representing in the process.
> * This may be a silly question, but why can't you override a protected > method? Surely there is some very good reason for java developers > deciding not to allow this?! Sure you can. Specifically from the JLS: If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
Ben Phillips - 07 Jan 2008 04:48 GMT > Sure you can. Specifically from the JLS: > If the overridden or hidden method is protected, then the overriding or > hiding method must be protected or public; otherwise, a compile-time > error occurs. Hrm. This suggests that adding a private method to a class might break a subclass if that subclass defines a nonprivate method with the same name. I would hope that this isn't the case! What does the JLS say about it? I don't have a copy handy.
Lew - 07 Jan 2008 05:30 GMT >> Sure you can. Specifically from the JLS: >> If the overridden or hidden method is protected, then the overriding [quoted text clipped - 5 lines] > name. I would hope that this isn't the case! What does the JLS say about > it? I don't have a copy handy. <http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html>
There's no breakage because the subclass cannot see the superclass's private method. It is free to declare its own private, package-private, protected or public methods of the same name with compatible or incompatible signatures.
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8>
 Signature Lew
Eric Sosman - 07 Jan 2008 13:44 GMT >> Sure you can. Specifically from the JLS: >> If the overridden or hidden method is protected, then the overriding [quoted text clipped - 4 lines] > subclass if that subclass defines a nonprivate method with the same > name. I would hope that this isn't the case! [...] Other way 'round, I think: Adding a non-private method to a superclass might break an existing subclass that defines a private method with the same name and signature. Or in general, adding a more-accessible method to the superclass can break a subclass whose less-restrictive method suddenly becomes an override instead of a free-standing "voluntary" method.
In an ideal world this wouldn't happen, and even in the real world it doesn't happen often after the first few flailings at an initial design. Adding a non-private method to a superclass is a change in that class' "contract" with its clients; when a contract is rewritten you have to expect some negotiations among all the parties. It's a step not taken lightly -- but it is occasionally taken, as when Vector was retrofitted with the List interface.
 Signature Eric Sosman esosman@ieee-dot-org.invalid
Eric Sosman - 07 Jan 2008 13:52 GMT > [...] Or in general, adding a > more-accessible method to the superclass can break a subclass whose > less-restrictive method suddenly becomes an override [...] "Less-accessible," of course. >sigh<
 Signature Eric Sosman esosman@ieee-dot-org.invalid
Eric Sosman - 05 Jan 2008 22:08 GMT > Hello > [quoted text clipped - 13 lines] > a) Why does compiler only look at public methods in superclasses of > A? It doesn't: It looks at *accessible* methods in A and in its superclasses. The exact meaning of "accessible" depends on where the call is: private, package-private (default), protected, and public grant or deny access based on the relative "locations" of the call and the potential callee.
> b) besides, doesn't compiler also look at methods ( in superclasses of > A ) which have default access specified ( it does on my system )? I > find it strange that author of the book would forget to mention that Package-private methods of A and its superclasses will be eligible for consideration if the point of call is in the same package. If the point of call is in some other package, the package-private methods are inaccessible and won't be considered.
> c) If compiler does look for both default and public methods in A's > superclasses, then why doesn't it also look for methods with protected > access modifier? Again, it depends on where the call is located. If the call is inside A, then the protected methods of A's superclasses are eligible for consideration. If the call is not in the hierarchy and not in the same package, protected methods are off-limits.
It seems to me you may have missed some precondition in what the author wrote, like "If a method in class package1.B [page turn; start reading here] calls a method in package2.A, the compiler considers the following methods as potential call targets: ..." Or perhaps the author was sloppy and failed to explain the circumstances of the call he was trying to elucidate. I'd suggest a re-read, including a quick look at the preceding page to see if there's an "In the following discussion" paragraph that outlines the assumptions.
> 2) In the next step compiler determines the types of parameters > supplied in the parameter call and finds exact or best match ( this [quoted text clipped - 10 lines] > was declared only in one of A's superclasses ( with private access > modifier ), then compiler would report an error and nothing else. The author is probably trying to point out that some method calls can be completely resolved at compile time, while others cannot be fully sorted out until run time. Look at this case (don't worry about how pointless it seems)
class A { void m1() { System.out.println("A's m1"}; } void m2() { m1(); } }
Inside m2, can the compiler be sure that A's own m1 is called? No, because the class A might have been extended by some other class B that overrides m1:
class B extends A { void m1() { System.out.println("B's m1"); } }
Now if you create a B instance and call it's m2 method (which it inherits from A), A's m2 will wind up calling B's m1 instead of A's own m1. The final determination of whether A's or B's m1 is called cannot be made until run-time, depending on the actual A-ness or B-ness (or C-ness, or ...) of the object on which m2 is invoked.
But if m1 were final, or private, or static, it could not be overridden. In this case, the compiler *can* discover that A's m2 can only call A's m1, and not some other m1.
However, this seems like information someone who's only been looking at Java for a week probably doesn't need. I'm not sure why the author of a beginner-level text would burden you with it.
> * This may be a silly question, but why can't you override a protected > method? Surely there is some very good reason for java developers > deciding not to allow this?! "Why doesn't the Sun rise in the East?" That is, you *can* override a protected method. You cannot override it with a private or package-private method (overriding can loosen the access restrictions, but cannot tighten them), but you can override with a protected or public method.
 Signature Eric Sosman esosman@ieee-dot-org.invalid
failure_to@yahoo.co.uk - 06 Jan 2008 00:45 GMT hello
> > c) If compiler does look for both default and public methods in A's > > superclasses, then why doesn't it also look for methods with protected [quoted text clipped - 14 lines] > page to see if there's an "In the following discussion" paragraph > that outlines the assumptions. I'm actually reading "Java, the complete reference" by Herbert Schildt. But I also have another book called Core Java 2. Now for the most part I only use the complete reference book, but since this book doesn't tell the steps taken when resolving a method call, I looked it up in core Java 2. So yes,I didn't read the preceding pages ( partly because I noticed that Core Java 2 relies on applets to show examples, while the complete reference doesn't mention applets for some time )
1)
> A protected method is accessible from subclasses anywhere, *and* > throughout its own package, whether in subclasses or not. If I'm not mistaken, protected method can be accessed from subclasses anywhere, but these subclasses ( assuming they are in another package ) can only call these protected methods on objects of the same type as calling subclasses themselves? Thus:
class A{ protected void a(){...} } class B extends A { // class B is in another package public static void main( string[] args ){
B b = new B(); b.a(); // allowed
A a1 = new A(); a1.a(); // not allowed
} }
Now B class( either inside class B static methods or inside B class objects ) can only call method a() on objects of class B, but not on objects of class A?!
2) I apologize for asking another question, but still ...
I noticed that objects of same class can call each others private methods and members:
public static void main(String [] args){ A a = new A(); A a1 = new A();
a.c ( a1 ); // with this call we access private member of object a1 }
class A{ private int i = 16; public void c( A u ){ System.out.println(u.i); } }
So basically there is no way for object to hide its private members from other objects of same type?
thank you
Eric Sosman - 06 Jan 2008 16:02 GMT > [...] > I'm actually reading "Java, the complete reference" by Herbert > Schildt. [...] I'm not familiar with this book. However, at least two of this author's other books on programming languages are said to be somewhat less than perfectly accurate. There's a Wikipedia article about Mr. Schildt, and some of the links it provides make for interesting if disheartening reading.
>> A protected method is accessible from subclasses anywhere, *and* >> throughout its own package, whether in subclasses or not. [quoted text clipped - 20 lines] > objects ) can only call method a() on objects of class B, but not on > objects of class A?! Right. B's code is also unable to call method a() on objects of some other class C that also extends A. Roughly speaking, protected access must "go through channels" by travelling up the inheritance hierarchy. The reasons for this may become clearer if you ponder some of the ways that protected is used: For example, look at the protected member modCount in java.util.AbstractList, and consider how it is used by subclasses like java.util.ArrayList.
> 2) > I apologize for asking another question, but still ... [quoted text clipped - 4 lines] > So basically there is no way for object to hide its private members > from other objects of same type? Right. Accessibility follows the organization of the classes, not the organization of individual class instances. If you don't want two instances of your class to peek at each other's private members, just refrain from writing code that peeks! The code is inside your class and under your control; you can make your own rules about what is and isn't done.
 Signature Eric Sosman esosman@ieee-dot-org.invalid
Patricia Shanahan - 06 Jan 2008 16:25 GMT >> [...] >> I'm actually reading "Java, the complete reference" by Herbert [quoted text clipped - 5 lines] > article about Mr. Schildt, and some of the links it provides > make for interesting if disheartening reading. ...
I made the mistake of buying a book by him on C++. I stopped reading it when I found an example program that was atrociously and gratuitously non-portable. The problems in that program were basic C stuff, and therefore obvious to me, but I was worried that there might be other, equally bad, ideas in the book that I would not detect so easily.
In general, I am dubious about Java books that claim to be a "reference". The combination of the Java Language Specification and the API documentation is a fine reference, but a very bad tutorial. The OP probably needs an introduction to Java that aims to explain and introduce the material, not serve as a reference.
Patricia
Lew - 06 Jan 2008 17:41 GMT >>> [...] >>> I'm actually reading "Java, the complete reference" by Herbert [quoted text clipped - 12 lines] > therefore obvious to me, but I was worried that there might be other, > equally bad, ideas in the book that I would not detect so easily. This raises the interesting question of how such a one becomes a repeatedly published author if the public wisdom is that they are not knowledgeable or accurate. It makes one wonder further about the integrity or reliability of the publisher.
 Signature Lew
Patricia Shanahan - 06 Jan 2008 18:18 GMT >>>> [...] >>>> I'm actually reading "Java, the complete reference" by Herbert [quoted text clipped - 17 lines] > knowledgeable or accurate. It makes one wonder further about the > integrity or reliability of the publisher. I think he writes very readably.
Personally, I would rather have accurate information even if I have to think and dig a bit. I'm the sort of person who goes into a demanding CS Ph.D. program for the fun of it. Also, when I learn a programming language I aim to reach expert skill level as soon as possible, so I don't want the difficult parts hidden from me. C++ considering only little-endian 16 bit int systems really is simpler than portable C++ programming, but I knew I wanted to learn the latter.
I suspect most of the criticism has come from people with similar attitudes.
Also, the publisher may have worked around the problem by having his work checked by people who actually know the subject. I have not looked at his Java books.
Patricia
Daniel Dyer - 06 Jan 2008 22:54 GMT > I think he writes very readably. > [quoted text clipped - 12 lines] > work checked by people who actually know the subject. I have not looked > at his Java books. I own two of his books. I've got "Java Programmer's Reference", which I purchased in 1997 when I was student (it was cheaper than most of Java books). This is relatively small book (compared to his weighty "Complete Reference"). I haven't used it for years, so I've just grabbed it off the shelf to see if the criticism is valid. The first few chapters just list all of the concepts, keywords and operators and briefly explain what they do. The second part of the book lists all of the classes and methods in (the 1.1 verions of) the lang, util, io, net, applet and awt packages - with a 1 or 2 line description of each. This is obviously all stuff that you find very easily online and adds nothing to the API docs or Sun's tutorial. However, at the time I did not have net access at home, so I found the book a handy reference when learning to program in Java.
I also own the equivalent C/C++ book, purchased around the same time, which is currently sitting on my desk at work. I rarely program in C or C++ so I often forget the details. The book is reasonably useful for quickly looking things up. It seems OK, though I doubt I am an accomplished enough C or C++ programmer to be able to spot subtle problems.
Dan.
 Signature Daniel Dyer http://www.uncommons.org
Arne Vajhøj - 06 Jan 2008 23:02 GMT >> This raises the interesting question of how such a one becomes a >> repeatedly published author if the public wisdom is that they are not [quoted text clipped - 10 lines] > little-endian 16 bit int systems really is simpler than portable C++ > programming, but I knew I wanted to learn the latter. Schildts books are not for you then.
But not everyone is at your level.
Schildt write for the millions of Mort's out there.
Arne
Arne Vajhøj - 06 Jan 2008 22:57 GMT >>>> [...] >>>> I'm actually reading "Java, the complete reference" by Herbert [quoted text clipped - 17 lines] > knowledgeable or accurate. It makes one wonder further about the > integrity or reliability of the publisher. It is all about the goal they want to achieve.
If you want a book to describe the finer points in the language absolutely correct, then Schildt is not the author to ask.
If you want a book that can explain a beginner how to write Hello World, then Schildt writes excellent books.
I learned C from one of his books.
I have never read a Java book by him, but I am envisioning it something like "In java each class is in its own file". And all the Java gurus will point out that it is not correct. And if the same Java gurus wrote a book it would be "In java each top level public class is in its own file" and the readers will close the book after reading that and learn Python instead.
Arne
Wildemar Wildenburger - 07 Jan 2008 00:46 GMT > I have never read a Java book by him, but I am envisioning it > something like "In java each class is in its own file". And all > the Java gurus will point out that it is not correct. And if the > same Java gurus wrote a book it would be "In java each top level > public class is in its own file" and the readers will close the > book after reading that and learn Python instead. You make that sound like it's a bad thing.
;) /W
Joshua Cranmer - 06 Jan 2008 19:06 GMT > In general, I am dubious about Java books that claim to be a > "reference". The combination of the Java Language Specification and the > API documentation is a fine reference, but a very bad tutorial. The > OP probably needs an introduction to Java that aims to explain and > introduce the material, not serve as a reference. Don't forget about the Java VM spec--it gives some insight on how Java works in a bit more detail than the JLS. I'm still wondering why there's no third edition yet; reading the addendums is very annoying since they only amend the class file format (considerably--5's addendum is ~80 pages and 6's addendum is well over a hundred) and a tiny bit in the instruction set.
Anyways, the Java Tutorial is a very good tutorial into the material, with the added benefit that other tutorials that Sun provides can detail some of the more confusing aspects a bit better.
 Signature Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
failure_to@yahoo.co.uk - 06 Jan 2008 21:10 GMT this sucks. I'm 300 pages into the book ( well I skipped String handling, generics and exploring java.lang chapters - will deal with them later, since I first want to deal with IO chapters ) ... uh
Anyways, thank you kindly for helping me
Arne Vajhøj - 06 Jan 2008 22:49 GMT >> [...] >> I'm actually reading "Java, the complete reference" by Herbert [quoted text clipped - 3 lines] > this author's other books on programming languages are said to > be somewhat less than perfectly accurate. Schildt is favorite target for C and C++ language lawyers due to some of the stuff he has written.
In my opinion the criticism is out of proportions even though it is correct.
He writes books that are easy to read for for beginners. And if they learn to program, then they will eventually also get rid of the misunderstandings.
Arne
Patricia Shanahan - 05 Jan 2008 22:33 GMT ...
> Say we have class A reference variable called a. According to my book, > when a.x() is called, the following steps take place ( I won't write [quoted text clipped - 3 lines] > 1) Compiler enumerates all methods in class A and all public methods > in the superclasses of A to find methods named x ...
Maybe you should consider looking for a different book. Either the book is seriously inaccurate, or there is something about how it is written that is confusing to you. Reading it is not giving you an accurate impression of how Java behaves.
Patricia
Mark Space - 05 Jan 2008 22:47 GMT > a) Why does compiler only look at public methods in superclasses of > A? Well, it doesn't really, but basically that's "by design." In other words programmer need some way to encapsulate code, and the public/private modifiers were chosen by Sun as the way to implement encapsulation.
> c) If compiler does look for both default and public methods in A's > superclasses, then why doesn't it also look for methods with protected > access modifier? Your book is defective. Get a better one. In particular:
Default access methods are "package private." They can be accessed like public methods from other classes in the same package. From outside a package, the are effectively private.
Protected methods can be access only by classes which are subclasses of the class. Everything else is sees them as effectively private.
> Why point out that if method is private then compiler knows what > method to call? I'm assuming that book is only talking about the case > where private method x() is defined in class A and not in one of A's > superclasses?! Yes it has to do with inheritance. However, since private methods are only accessible by the class itself (or an inner class), it really only has to do with name resolution inside of the class or a subclass. You might want to check that out and make sure you understand the different types of inheritance too, as well as accessibility modifiers.
> * This may be a silly question, but why can't you override a protected > method? Surely there is some very good reason for java developers > deciding not to allow this?! See protected methods above.
Eric Sosman - 05 Jan 2008 23:14 GMT > [...] > Default access methods are "package private." They can be accessed like [quoted text clipped - 3 lines] > Protected methods can be access only by classes which are subclasses of > the class. Everything else is sees them as effectively private. That's not quite right. A protected method is accessible from subclasses anywhere, *and* throughout its own package, whether in subclasses or not.
To the O.P.: If you think of the progression from private to default (package-private) to protected to public as always adding accessibility and never removing it, you'll be pretty close to the truth. There are some exceptions involving classes nested inside other classes -- keep reading, they'll turn up -- but that's the broad outline.
 Signature Eric Sosman esosman@ieee-dot-org.invalid
Mark Space - 05 Jan 2008 23:18 GMT > That's not quite right. A protected method is accessible > from subclasses anywhere, *and* throughout its own package, whether > in subclasses or not. Ah good point. Makes sense though....
Roedy Green - 06 Jan 2008 07:03 GMT >a) Why does compiler only look at public methods in superclasses of >A? The literal answer is because that is the definition of public. I gather what you are asking is "why did they define it that way rather than some other?" What is your proposed alternate?"
See http://mindprod.com/jgloss/public.html http://mindprod.com/jgloss/scope.html
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
EJP - 07 Jan 2008 00:08 GMT > According to my book, Could you please tell us the title, author, and publisher of this terrible book so we can (a) avoid it, (b) recommend against it, and (c) complain to the publisher?
> I find it strange that author of the book would forget to mention that I find it even stranger that the technical reviewers of the book didn't pick all this nonsense up. Are you sure you're quoting it accurately?
failure_to@yahoo.co.uk - 07 Jan 2008 01:08 GMT > failure...@yahoo.co.uk wrote: > [quoted text clipped - 8 lines] > I find it even stranger that the technical reviewers of the book didn't > pick all this nonsense up. Are you sure you're quoting it accurately? Well book is called Core Java 2, Volume 1, but as I don't actually study from this book, it may very well be that author pointed out ( few pages earlier ) the fact that he is simplifying things. I don't want a guy to loose a million cause of little me.
Anyways, I'm gonna quote the first two steps from the book, since they appear to cause the most controversy:
"It is important to understand what happens when a method call is applied to an object. Here are the details:
1) the compiler looks at the declared type of an object and the method name. Let's say we call x.f(param), and the implicit parameter x is declared to be an object of class C. Note that there may be multiple methods, all with the same name, f, but with different parameter types. For example, there may be a method f(int) and a method f(String). The compiler enumerates all methods called f in the class C and all methods called f in the superclasses of C Now the compiler knows all possible candidates for the method to be called
2) Next, the compiler determines the types of parameters that are supplied in the parameter call. If among all the methods called f there is a unique method whose parameter types are best match for the supplied parameters, then that method is choosen to be called. This process is called overloading resolution. The situation can get complex because of type conversions ( int to Double and so on ). If compiler cannot find any method with matching parameter types or if multiple methods all match after applying conversions, then compiler eports an error. Now the compiler knows the name and parameter types of the method that needs to be called"
cheers
EJP - 08 Jan 2008 03:19 GMT > Anyways, I'm gonna quote the first two steps from the book, since > they appear to cause the most controversy: Thanks. The word 'public' does not appear in the text you've quoted. So there's nothing wrong with the *book*. You just made it up.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|