• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

meyer q.61

 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here's another one I didn't get from the Meyer mock:

class sup {
void method() throws Exception { }
}

class test extends sup {
public static void main(String[] args) { //1
sup s = new test();
s.method();
}

void method() {} // 2
}

What can be done to avoid compiler error?

---------------

a. Add a "throws Exception" clause at line 1 <---- first correct answ.
b. Add a "throws Exception" clause at line 2
c. Use a try catch block when calling s.method(). <--- second correct answ.
d. There is no compile error. <--- my answer
e. None of the above.

----------------

As I recall, override rules say that you can use the same, fewer, or
sub-types of exceptions from the overridden method in the overriding
method. The overriding version states no exceptions, which is valid.
But the compiler still requires that an exception be handled or declared.
Why?
 
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the reference declared is a sup reference (superclass) and it is handed a reference to a test (subclass) object, polymorphism is in play. When the is the case, the compiler is going to require that you construct the code to handle each possible type of object whether YOUR code does it or not. The compiler isn't going to assume that the super reference will ONLY hold the subclass type....rather, it will have you code the try catch block so that either object could be put into the reference.
 
Ken Truitt
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks--excellent explanation
 
We don't have time to be charming! Quick, read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic