wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes why doesnt the compiler warn or check this ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why doesnt the compiler warn or check this ?" Watch "why doesnt the compiler warn or check this ?" New topic
Author

why doesnt the compiler warn or check this ?

Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

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 :



SCJP 6. Learning more now.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Because often it's a bad idea, but sometimes its not.


[Jess in Action][AskingGoodQuestions]
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

Ernest Friedman-Hill wrote:Because often it's a bad idea, but sometimes its not.


Please elaborate.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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

Joined: Nov 18, 2008
Posts: 433
    
    2
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

Joined: Mar 27, 2011
Posts: 32

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why doesnt the compiler warn or check this ?