×

Discussion Board

Results 1 to 2 of 2
  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    7

    making an argument readonly.

    I come from a C++ background and I'm just starting to program java. I was thought to put 'const' everywhere. I soon discovered that in Java, you have const, and final. but you can't use it everywhere. for example, next segment.

    Code:
    void foo( aClass anObject)
    {
       anObject.ModifyMe();
    }
    the object will be modified.

    I haven't found a way that i can make it not modifiable.
    it tried:
    Code:
    void foo(final aClass anObject)
    {
       anObject.ModifyMe();
    }
    but that finals the pointer, and not the reference to the object. so you can still adjust the object.

    How can i make sure, that I, or anybody else can never modify the object in that function?
    Last edited by wooks; 2010-05-26 at 15:10.
    Kind Regards
    Wooks

  2. #2
    Super Contributor
    Join Date
    Jun 2003
    Location
    Cheshire, UK
    Posts
    7,395

    Re: making an argument readonly.

    There is no specific way to do what you want. The only way to have an object, the contents of which cannot be modified, is for that object not to have any "setter" methods. For example, String works that way.

    If you want a mutable object, but have the setter methods inaccessible, there are various ways to do it. For example, if the class is in a different package, give the setter methods default scope, so that classes in other packages cannot see them.

    Alternatively, create an interface for the getter methods.

    Code:
    public interface Readable {
        public Object getValue();
    }
    Code:
    public class Data implements Readable {
        private Object value;
    
        public Object getValue() {
            return value;
        }
    
        public void setValue(Object value) {
            this.value = value;
        }
    }
    Code:
    public void doSomething(Readable r) {
        // can't change the contents of "r"
        Object o = r.getValue();
    }
    Graham.

Similar Threads

  1. Replies: 2
    Last Post: 2009-05-22, 06:40
  2. Parsing file content
    By hendrawan.ashari in forum Symbian
    Replies: 7
    Last Post: 2007-03-09, 10:41
  3. Replies: 4
    Last Post: 2005-04-25, 17:06
  4. D211 with RH7.3
    By fiveam in forum Multimodecards
    Replies: 3
    Last Post: 2003-02-24, 09:06
  5. Problem with Nokia D211 Linux Drivers
    By fiveam in forum Multimodecards
    Replies: 1
    Last Post: 1970-01-01, 02:00

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •