• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why doesnt the compiler warn or check this ?

 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I declare a member variable private in a class. Then, i let one of the member methods return a reference to that private variable. This seems to be dangerous to me. I compile one such program and ran it successfully. Why doesnt the compiler prevent/warn me from returning a reference to a private variable ?

here is my program which works :


 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because often it's a bad idea, but sometimes its not.
 
Rahul Sudip Bose
Ranch Hand
Posts: 637
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:Because often it's a bad idea, but sometimes its not.


Please elaborate.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Returning a reference to a private immutable member is always OK, obviously. The compiler doesn't know which types are immutable, though, so it could not use that as a guideline. But there are also plenty of classes that deliberately return references to mutable members. The "XBuffer" classes in java.nio even return references to a private array member.
 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to get warnings about such potential dangerous coding problems you could incorporate a code analysis tool like PMD or Findbugs into your build process (e.g. Maven) or IDE.
 
kumarjit banerjee
Ranch Hand
Posts: 32
Eclipse IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rahul Sudip Bose wrote:I declare a member variable private in a class. Then, i let one of the member methods return a reference to that private variable. This seems to be dangerous to me. I compile one such program and ran it successfully. Why doesnt the compiler prevent/warn me from returning a reference to a private variable ?

here is my program which works :





This is because you may need to modify a private member of a class so java allows you to do that through getters and setters.
Your method acts likely as getters. So this is as expected. Reffering to the term "immutable" the setters methods sets the values of the variables, if immutable then a new object is assigned to the reference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic