• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Possible inaccuracy in Sybex CSG 17, p. 373, Sealed Classes

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
On page 373, the following infobox is printed:

Real World Scenario "Why Have Sealed Classes?"
In Chapter 3, “Making Decisions,” you learned about switch expressions and pattern
matching. Imagine if we could treat a sealed class like an enum in a switch expression by
applying pattern matching. Given a sealed class Fish with two direct subclasses, it might
look something like this:

If Fish wasn’t sealed, the switch expression would require a default branch, or the
code would not compile. Since it’s sealed, the compiler knows all the options! The good
news is that this feature is on the way, but the bad news is that it’s still in Preview in Java 17 and not officially released. We just wanted to give you an idea of where some of these new features were heading.


When enabling the preview feature and running a similar code example, the compiler returned this:

error: the switch expression does not cover all possible input values

The switch expression would only compile if a case for the Fish class itself was added after the other two case statements. The method with the switch expression is just a code example to illustrate a point, that gets obvious anyway. But maybe it should be changed anyway so that the example is correct.

The Fish case would have to come after the other two cases, otherwise the compiler reports:

error: this case label is dominated by a preceding case label

Another solution for the last problem would be to make the Fish class abstract.
 
It would give a normal human mental abilities to rival mine. To think it is just a tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic