Win a copy of Serverless Applications with Node.js this week in the NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

Can someone please help with this casting question?  RSS feed

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why there is a compile error in line 16? If we comment out line 16, line 17 will print "DerivedA". Thank you so much in advance!

 
Marshal
Posts: 63827
209
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Doubtless you already know you should make all fields private, but the real problem is to do with polymorphism. Polymorphism apples to instance methods full stop  Not static methods, not fields of any kind. So line 17 gives you the subclass' version.
Fields are not polymorphic; whichever field you get depends on the declared type of the variable, which, by the way, makes it a very bad idea to have fields with the same name in superclass and subclass. Never mind whether you cast or not, the declared type of b2 is Base, and Base doesn't have that field in the first place. So the compiler can't find the field from the Base class, and cannot therefore allow the code to run.
Try this instead:-
 
Nan Jordan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for your reply!  I tried the following, it works but i am even morning confused... Why casting b2 in a separate statement doesn't work but this one works.

 
Bartender
Posts: 4097
63
Chrome Fedora Hibernate
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's actually the reference type, when you do it in a separate line you still assigning it to the same "Base" type (so line #15 has no effect to line #14 technically). So you can refer whatever available in "Base" type.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Nan Jordan wrote:. . . Why casting b2 in a separate statement doesn't work . . .

Because the cast is only effective in the right half of line 16. It doesn't change the declared type, so it reverts to Base n line 17.
 
Nan Jordan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So does it mean line 15 is a invalid statement? We should never use casting like that?
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, line 15 doesn't actually do anything; it is a statement with no effect.
 
Ranch Hand
Posts: 89
IntelliJ IDE Java Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nan Jordan,

Welcome to the Ranch . I think you should read about upcasting and downcasting. This link http://www.cs.utexas.edu/~cannata/cs345/Class%20Notes/14%20Java%20Upcasting%20Downcasting.htm seems to offer a pretty good example which ought to clear up your doubts.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is quite a good example, even though it speaks of child and parent classes. Those terms can be misleading because they could make people think that computer inheritance is like genetic inheritance.
What the article doesn't say is that using instanceof and lots of casts suggests there is something wrong with your program design. Avoid both as much as possible.
 
Nan Jordan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much everyone!
 
Ranch Hand
Posts: 99
Java Linux Monad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Welcome to the Ranch

Doubtless you already know you should make all fields private, but the real problem is to do with polymorphism. Polymorphism apples to instance methods full stop  Not static methods, not fields of any kind. So line 17 gives you the subclass' version.
Fields are not polymorphic; whichever field you get depends on the declared type of the variable, which, by the way, makes it a very bad idea to have fields with the same name in superclass and subclass. Never mind whether you cast or not, the declared type of b2 is Base, and Base doesn't have that field in the first place. So the compiler can't find the field from the Base class, and cannot therefore allow the code to run.
Try this instead:-



Not really sound advice. I use final public fields all the time. Hell I know of programming languages that encourage all data to be immutable and visible. Java encourages fields to be private because it embraces some ideas within OOP but that doesn't mean there isn't times when public fields makes sense. I can think of one right now... A Pair<T.W> class.

 
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Several things wrong with that. First of all, a Pair class is degenerate in that it conveys no semantic meaning and should be avoided in preference for a data structure that is appropriate for the specific problem domain. That's why Java doesn't include a Pair class in the first place.

Now, it's fine to create classes that exposes their fields to other classes in the same package, but making fields public is always a big no no because you give up the ability to change the internal representation of the class without breaking backwards compatibility of your public API.

So while fields don't necessarily have to be private, they should definitely never be public.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Several things wrong with that. . . .

Another problem I can see: if the T or W are mutable reference types, it will be possible to change the state of a Pair object without that object “knowing” about it.
 
Stephan van Hulst
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's possible with any generic type, including the collection classes, so I don't think that's fair criticism.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All right, but I still think the only place for public fields is global constants.
 
Stephan van Hulst
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed.
 
Gerard Gauthier
Ranch Hand
Posts: 99
Java Linux Monad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Several things wrong with that. First of all, a Pair class is degenerate in that it conveys no semantic meaning and should be avoided in preference for a data structure that is appropriate for the specific problem domain. That's why Java doesn't include a Pair class in the first place.

Now, it's fine to create classes that exposes their fields to other classes in the same package, but making fields public is always a big no no because you give up the ability to change the internal representation of the class without breaking backwards compatibility of your public API.

So while fields don't necessarily have to be private, they should definitely never be public.



Again! This endorses a strict OPP view which is falling out of favor in the mainstream. Yes you do expose the internals of the data but you have to expose something in an object for it to be accessible. In OOP the favored idea is to have objects which have visible methods.  The idea that its OK to expose some methods of an object while forbidding others is flawed. The designer of the class has to consider its usage before committing to a public interface.
 
Stephan van Hulst
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Gerard Gauthier wrote:This endorses a strict OPP view which is falling out of favor in the mainstream.


What sources do you have to support this? Who is this mainstream? What applications are they writing?

Yes you do expose the internals of the data but you have to expose something in an object for it to be accessible.


Yes, that would be accessor methods. If Java had full-fledged properties I would be 100% behind that instead, but alas, it doesn't so we need to use methods for public APIs.

The idea that its OK to expose some methods of an object while forbidding others is flawed.


Flawed how? Can you give anexplanation for this assertion?

The designer of the class has to consider its usage before committing to a public interface.


And in what use case is accessing a public field directly more appropriate than accessing it through a method? This point actually speaks against using public fields, because when I provide a method I can easily use the method handle in higher order functions, rather than having to use a lambda expression, making my code much more fluent.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Gerard Gauthier wrote:. . . This endorses a strict OPP view which is falling out of favor in the mainstream.

What makes you think a strict OO view is falling out of favour?

. . . objects which have visible methods.

Yes, that is correct. You keep the implementation details well hidden but the methods can expose a “result” obtained by using the implementation. That also allows you to change the implementation, such changes being “transparent” to other code.

The idea that its OK to expose some methods of an object while forbidding others is flawed. . . . .

No, that is a correct design principle. In fact you can start making every method private and give each a less restrictive access modifier as required.
 
Gerard Gauthier
Ranch Hand
Posts: 99
Java Linux Monad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Gerard Gauthier wrote:. . . This endorses a strict OPP view which is falling out of favor in the mainstream.

What makes you think a strict OO view is falling out of favour?

. . . objects which have visible methods.

Yes, that is correct. You keep the implementation details well hidden but the methods can expose a “result” obtained by using the implementation. That also allows you to change the implementation, such changes being “transparent” to other code.

The idea that its OK to expose some methods of an object while forbidding others is flawed. . . . .

No, that is a correct design principle. In fact you can start making every method private and give each a less restrictive access modifier as required.



What makes me think OOP is falling out of favour(not really falling out of favour but moving aside or back a bit)? How about Java implementing lambdas and streams? Look OOP was the dominate programming paradigm for roughly 2 decades and in that time the OOP community tried to fit that shoe on many different feet with some success stories and some not so success stories.

Just take a quick survey of the most popular languages.
Golang -> Strong support for higher order functions.
JavaScript -> Excellent support for higher order functions.
Ruby -> Excellent support for higher order function.
Python -> Excellent support for higher order functions.
Even C++ has made the plunge to support some features of higher order functions.

The trend has been to move towards higher order functions.

I'm not saying Java is dying or irrelevant. I'm saying the ideas Java was designed on are changing to meet the new demands of a modern world.
 
Stephan van Hulst
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object Oriented Programming and Functional Programming are not mutually exclusive. I also fail to see what higher order functions have to do with not exposing fields.
 
Gerard Gauthier
Ranch Hand
Posts: 99
Java Linux Monad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:Object Oriented Programming and Functional Programming are not mutually exclusive. I also fail to see what higher order functions have to do with not exposing fields.



Well along the posting trail, several questions were posted. I was addressing some of them.

You are 100% correct! OOP and functional programming are just tools from the same toolbox. They both have their pros and cons. They are both abstractions that, when exposed, have to deal with the constraints of the underlying hardware. So why higher order functional and functional programming concepts? Convenience and safety.

About exposing fields. Can you tell me what harm can occur if a field is visible but immutable? The only thing I can see is the value is public and available. You have to understand many languages favour visable immutable data over hidden mutable data.
 
Campbell Ritchie
Marshal
Posts: 63827
209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Gerard Gauthier wrote:. . . what harm can occur if a field is visible but immutable? . . . .

Quite a lot. For a start it fixes that part of the implementation for ever.  If a more efficient way to execute the program is found, it may be impossible to implement that without “breaking” client code. It makes refactoring and code maintenance more difficult.The 101.010101.... assumes that only 99% of the honey comprises sugar and water and 1% consists of something else, which gives the honey its flavour and colour. You now have an immutable object, until you watn to change it to this sort of thing:-That sort of change is now precluded, though it would have been easy with private fields throughout. I think all fields should be private, but, as Stephan says, the developers of a particular package may decide a different policy, that inside their package all fields may have package‑private access (officially called default access).
 
Stephan van Hulst
Saloon Keeper
Posts: 9996
208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The harm is that if you expose a public field, you're forever bound to that data format, because you can't change or remove the field without breaking backward compatibility. If at a later moment you decide that instead of just setting or getting that field, you want to add validation or you want to change your type into a proxy that delegates to a different object... well, you can't.

Unless your type is intended for serialization, its internal data structure is an implementation detail, and implementation details must not be exposed publicly.
 
We're all out of roofs. But we still have tiny ads:
global solutions you can do in your home or backyard
https://coderanch.com/t/708587/global-solutions-home-backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!